Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an easy way to create a trivial one-off Python object?

Tags:

python

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?

like image 287
mhagger Avatar asked Oct 17 '08 10:10

mhagger


1 Answers

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)
like image 136
gimel Avatar answered Oct 08 '22 23:10

gimel