user206545
user206545

Reputation:

Runtime injection of attributes into module namespace

When a python module I'm writing is imported, I want to create a set of attributes for the module based upon the contents of a dictionary defined in the same module. Here is a small portion of the dictionary from the module:

list_of_constellations = {
   0: Constellation("And", "Andromeda"),
   1: Constellation("Ant", "Antlia"),
   2: Constellation("Aps", "Apus"),
   3: Constellation("Aql", "Aquila"),
}

where Constellation is a namedtuple. What I want is to inject a new set of attributes into the namespace whose name is the first element in the tuple and whose value is the key. So, after importing, the following attributes can be used:

import constellations

print constellations.And   # prints 0
print constellations.Ant   # prints 1

How might I do this?

Upvotes: 4

Views: 1282

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122152

In the module itself, the globals() function returns the module namespace as a dictionary; simply use the first element of each named tuple as the key to set the integer values:

for key, const in list_of_constellations.items():
    globals()[const[0]] = v  # set "And" to 0, etc.

or from outside the module, use setattr() to add attributes to the module:

import constellations

for key, const in constellations.list_of_constellations.items():
    setattr(constellations, constellation[0], v)  # set "And" to 0, etc.

Upvotes: 4

siddharthlatest
siddharthlatest

Reputation: 2257

In Python 2.7:

>>> import constellations
>>> dir(constellations)
['Constellation', 'list_of_constellations', 'namedtuple', 'namespace', ...]
>>> for key, tupl in constellations.list_of_constellations.iteritems():
>>>    setattr(constellations, tupl[0], key)
>>> dir(constellations)
['And', 'Ant', 'Aps', 'Aql', 'Constellation', 'list_of_constellations',
'namedtuple', 'namespace', ...]

For Python3, replace iteritems() with items().

You can use vars(constellations).update(dict) over setting attributes individually, where dict is a dictionary object containing attributes to be inserted in the name:value format.

Upvotes: 1

Related Questions