I regularly have a group of (semantically) related dynamic variables that are accessed by multiple methods and altered during runtime. I am currently fluctuating between three ways of highlighting their "family" and reduce the conceptual clutter in main: variable name prefix, use a class, or use a dictionary.
Are any of these generally preferred (i.e., pythonic) or maybe something else entirely? I have a slight preference for classes:
# Prefix
key_bindings_chars = {'right': '->', 'left':'<-'}
key_bindings_codes = ['smooth', 'spiky']
key_bindings_hints = ['Smooth protrutions', 'Spiky protrutions']
print(key_bindings_chars['right'])
# As a class
class key_bindings(object):
chars = {'right': '->', 'left':'<-'}
codes = ['smooth', 'spiky']
hints = ['Smooth protrutions', 'Spiky protrutions']
print(key_bindings.chars['right'])
# As a dict
key_bindings = {
'chars': {'right': '->', 'left':'<-'},
'codes': ['smooth', 'spiky'],
'hints': ['Smooth protrutions', 'Spiky protrutions']
}
print(key_bindings['chars']['right'])
Creating distinct variables does not scale well if you decide to add functionality. A class without behavior (i.e. no methods) is pretty pointless as well. My opinion is that you should use the dictionary or named tuples.
>>> from collections import namedtuple
>>> KeyBindings = namedtuple('KeyBindings', 'chars codecs hints')
>>> Chars = namedtuple('Chars', 'right left')
>>>
>>> key_bindings = KeyBindings(Chars('->', '<-'), ['smooth', 'spiky'], ['Smooth protrutions', 'Spiky protrutions'])
>>>
>>> key_bindings.hints
['Smooth protrutions', 'Spiky protrutions']
>>> key_bindings.chars.left
'<-'
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