Python convention for naming variables to denote units

First, when I ask about elements, I mean units of measure, such as inches, feet, pixels, cells. I do not mean data types such as int and float.

Wikipedia refers to this as a type of logical data , rather than a physical data type .

I would like to know what is the best way to use variables.

Here is what code can go through what I ask:

board_length=8 #in inches board_length=8*12 #Convert from feet to inches 

Note that these are integers (or floats, I don't care), but I changed the units. Ive also kept the variable name the same. I could establish a convention, and that is the purpose of this question. Without a guide, I could do something like this:

 board_length=8 board_length_inches=8*12 

I would find this a random way to do something. Or, I can establish an agreement:

 Fboard_length=8 Iboard_length=8*12 

Or other options that I equally dislike. How can variables be described in a descriptive way, but as close to PEP-08 as possible?

To be as clear as possible, variables can have different data types, but the units will be the same (inches will have the same name, regardless of whether it was saved as an integer or integer),

+8
python naming-conventions pep8
source share
3 answers

I would go further and have separate types of objects that provide type safety, rather than just relying on naming conventions. Otherwise, you can pass a variable representing inches to a method that requires miles.

I think relying on naming conventions will be problematic for long-term use, and using types will give you much more flexibility and security (for example, providing conversions, etc. built into object types)

+1
source share

While you can come up with a naming convention, you might be better served by creating an object representing the "distance" with read / write properties in different units. For example:

 class Distance(object): def __init__(self): self._inches = 0 @property def inches(self): return self._inches @inches.setter def inches(self, value): self._inches = value @property def feet(self): return self._inches/12 @feet.setter def feet(self, value): self._inches = value * 12 

You can even make it more versatile so you can easily expand with new transformations. (Note: Edited this for memoize based on comments)

 from collections import defaultdict class Distance(object): _conversion_map = defaultdict(lambda: {'to' : None, 'from' : None}) def __init__(self, **kwargs): self._memo = {} if kwargs: unit, value = kwargs.iteritems().next() if unit == 'inches': self.inches = value else: setattr(self, unit, value) else: self.inches = 0 def __getattr__(self, name): if name in self._conversion_map: try: return self._memo[name] except KeyError: converter = self._conversion_map[name]['to'] if converter is None: raise AttributeError converted = converter(self.inches) self._memo[name] = converted return converted else: raise AttributeError def __setattr__(self, name, value): if name == '_memo': super(Distance, self).__setattr__(name, value) else: # Clear memoized values if setting the value of the object self._memo = {} if name == 'inches': super(Distance, self).__setattr__(name, value) if name in self._conversion_map: converter = self._conversion_map[name]['from'] if converter is None: raise AttributeError self._memo[name] = value self.inches = converter(value) else: raise AttributeError @classmethod def converter(cls, func): direction, unit = func.__name__.split('_', 1) cls._conversion_map[unit][direction] = func return func @Distance.converter def to_feet(value): return value / 12 @Distance.converter def from_feet(value): return value * 12 board_1_length = Distance(feet=2) board_2_length = Distance(inches=14) board_1_length.inches # 24 board_2_length.feet # 1 (integer division) 
+9
source share

If you need more reliable device support, you should check out the PyPi Pint module . It is not directly relevant to your naming question, but it may require most of the work with frequent conversions. Here you can find information about this and some other modules:

http://www.drdobbs.com/jvm/quantities-and-units-in-python/240161101

+2
source share

All Articles