Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use multiple variables or one dictionary

I'm new to Python and see a lot of source codes using separate variables for things such as x and y coordinates or min and max values.

ex.

COORD_X = 45  
COORD_Y = 65  
SIZE_MIN = 1  
SIZE_MAX = 10  

I was wondering why people didn't use dictionaries instead? And if I should follow their lead or do what feels better to me?

ex.

COORDS = {'x': 45, 'y': 65}  
SIZE = {'min': 1, 'max': 10}  

Is it a performance issue or am I missing something? Dictionaries seem like the better choice, especially if you have a lot of these sets of variable. It cuts your variables in half and you only need to pass one variable to functions instead of two.

like image 325
merote Avatar asked Oct 19 '25 13:10

merote


2 Answers

In many cases, it just comes down to personal style preferences. However, note that you're creating more objects to hold objects, which consumes more memory and has the performance hit of creation, as well as slightly slower lookup, so there would be instances (lots of objects, long running nested loops etc) where just having the multiple bindings would be benefitial.

For your examples, I'd probably use a namedtuple. The example there is pretty much your COORDS instance:

 >>> Point = namedtuple('Point', ['x', 'y'], verbose=True)
 >>> p = Point(11, y=22)
 >>> p.x + p.y
 33
like image 186
Matthew Trevor Avatar answered Oct 21 '25 03:10

Matthew Trevor


When you are writing in all caps, it usually denotes that that variable is a constant. This means that it is better you keep it that way. In your case, creating a dictionary for two key:value pairs is overkill. Dictionaries should be used for longer pairs.

If you are keen on using a dictionary in this case, the following would be a better approach:

CONSTANTS = {'COORD_X': 45, 'COORD_Y': 65, 'SIZE_MIN': 1, 'SIZE_MAX': 10}

Then you can do things like:

>>> CONSTANTS['COORD_X']
45

>>> print CONSTANTS.keys()
('COORD_X', 'COORD_Y', 'SIZE_MIN', 'SIZE_MAX')
like image 35
sshashank124 Avatar answered Oct 21 '25 02:10

sshashank124