indirect argument assignment

Donnal Walter donnal at
Sat Oct 12 21:49:52 CEST 2002

The following example is contrived in order to pose a few specific
questions; the actual application I have in mind is more complicated.
In a given class I want to create a large number of attributes (say
10-50) of different types (different classes) but with similar
constructor signatures. After each attribute is created I want to do
something else with it (such as add it to a list as in this example).

class ACompositeClass:
    def __init__(self):
        self.objectList = []
        self.attr1 = UserClassA('spam', 23)
        self.attr2 = UserClassZ('eggs', 42)

Although this code is straightforward enough, the following syntax
essentially reduces the number of lines in the __init__ statement by
half, at the expense of adding only a three-line method.

class ACompositeClass:
    def __init__(self):
        self.objectList = []
        self.Add(UserClassA, 'attr1', 'spam', 23)
        self.Add(UserClassZ, 'attr2', 'eggs', 42)

    def Add(self, type, name, arg1, arg2):
        self.__dict__[name] = type(arg1, arg2)

In the real application from which this made-up example was derived,
the Add() method does a lot more work that would be cumbersome to do
in the __init__() method, so my questions are not really about
efficiency (or even about clarity) but about safety and acceptability.

1. In Tutorial Section 9.2 it says, "Most namespaces are currently
implemented as Python dictionaries, but that's normally not noticeable
in any way (except for performance), **and it may change in the
future**." (emphasis mine) Therefore, is the following statement safe
as far as future compatibility is concerned?

        self.__dict__[name] = type(arg1, arg2)

Is there a better Python idiom to do the same thing? Is there a more
Pythonic way to write the third line of the Add() method?

2. I read somewhere once that one should avoid using local names that
are common Python words (such as "type") even if they aren't Python
keywords. Instead of positional arguments for Add(), however, I intend
to use keyword arguments, and "type" seems to be the most intuitive
argument name. Is this likely to get me in trouble?

More information about the Python-list mailing list