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.
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
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With