-1

in the following code snippet:

import cv2 for color_space in (cv2.COLOR_RGB2HSV, cv2.COLOR_RGB2LUV, cv2.COLOR_RGB2HLS, cv2.COLOR_RGB2YUV, cv2.COLOR_RGB2YCrCb): *print_it_as_name(color_space)* 

With which real statement can I replace print_it_as_name such that the output is

cv2.COLOR_RGB2HSV cv2.COLOR_RGB2LUV cv2.COLOR_RGB2HLS cv2.COLOR_RGB2YUV, cv2.COLOR_RGB2YCrCb

Without hardcoding it using if statements?

3
  • 2
    Just enclose it in quotation marks ''? If you want to work with variables dynamically you can always use their names as strings and obtain the corresponding values via getattr. Commented Feb 27, 2017 at 11:19
  • But I can't help feeling there's a deeper problem here, to which the usual answer is "use a dict". Commented Feb 27, 2017 at 11:24
  • Exactly, I have updated the question accordingly. Commented Feb 27, 2017 at 11:25

3 Answers 3

3

As others suggested, use a dict.

import cv2 data = { 'cv2.'+att : getattr(cv2, att) for att in ('COLOR_RGB2HSV','COLOR_RGB2LUV',...) } print(data.keys()) 

If you need all the COLOR_* attributes, you can avoid the hard coded list:

data = { ... for att in dir(cv2) if att.startswith('COLOR_') } 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but that really is not the point. I want to iterate over these values and uses these values later in the code, but also print the name of these values out.
@user1934212 I see. See my other answer then.
3

Use a reverse-map, mapping from the value, to its original name (assuming values are unique).

import cv2 reverse_map = { v:k for k,v in dir(cv2) if k.startswith('COLOR_') } for color_space in (cv2.COLOR_RGB2HSV, cv2.COLOR_RGB2LUV, cv2.COLOR_RGB2HLS, cv2.COLOR_RGB2YUV, cv2.COLOR_RGB2YCrCb): print(reverse_map[color_space]) 

Comments

1

Ok I've come up with a little hack to work this out using eval:

for color_space in ("cv2.COLOR_RGB2HSV", "cv2.COLOR_RGB2LUV", "cv2.COLOR_RGB2HLS", "cv2.COLOR_RGB2YUV", "cv2.COLOR_RGB2YCrCb"): print(color_space) # prints the name of the variable print(eval(color_space)) # prints the actual value of the variable. 

Probably not good practice to actually do this, I would recommend the dictionary approach but since you asked for it this way this is how its done.

4 Comments

My bad: I didnt give you the whole problem in my first post. Please see the edit.
Ah sorry for canging the rules of the game again: But I wouldnt bother, if I did not want to use the actual statements cv2.COLOR_RGB2HSV... later in the code. So I really want to iterate over these. Is there no reflection module in python?
@user1934212 sorry but I have no idea ^^
@MukeshIngham This is no good use case for eval, you should use getattr instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.