Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to hold related variables?

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'])
like image 356
Jonas Lindeløv Avatar asked May 29 '18 09:05

Jonas Lindeløv


1 Answers

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
'<-'
like image 174
timgeb Avatar answered Sep 18 '22 13:09

timgeb