I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:
options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
Of course I could use a dictionary, but options.VERBOSE
is more readable and easier to type than options['VERBOSE']
.
I thought that I should be able to do
options = object()
, since object
is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using object()
doesn't have a __dict__
member, and so one cannot add attributes to it:
options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?
The collections module has grown a namedtuple function in 2.6:
import collections
opt=collections.namedtuple('options','VERBOSE IGNORE_WARNINGS')
myoptions=opt(True, False)
>>> myoptions
options(VERBOSE=True, IGNORE_WARNINGS=False)
>>> myoptions.VERBOSE
True
A namedtuple is immutable, so you can only assign field values when you create it.
In earlier Python versions, you can create an empty class:
class options(object):
pass
myoptions=options()
myoptions.VERBOSE=True
myoptions.IGNORE_WARNINGS=False
>>> myoptions.IGNORE_WARNINGS,myoptions.VERBOSE
(False, True)
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