I am quite new to Python and I don't know what is available. Currently, I have this piece of code to quickly put some named variables together, so I can use them in other places:
props = namedtuple('props', '')
props.color = "green"
props.size = "large"
props.wheels = 4
props.roof = True
Is in this case the
namedtuple a good solution? Or can it be simpler?
Best How To :
namedtuple is excellent tool to produce fixed-sized pieces of (immutable) information, just like tuples but with named attributes for convenience.
However, you are using the
namedtuple class factory incorrectly.
props is a class, you normally would use it like this:
Props = namedtuple('Props', 'color size wheels roof')
props = Props(color="green", size="large", wheels=4, roof=True)
props immutable (the end-user can generate a new instance by using the
namedtuple._replace() method), and indexable as well.
The only reason you didn't run into issues with your approach is that you create a new class object each time your function runs; the class attributes you set on it are not shared between instances because no instances are ever created.
If you didn't want an immutable object, use a dictionary instead: