indirect argument assignment

Bjarke Dahl Ebert bebert at worldonline.dk
Sat Oct 12 16:36:14 EDT 2002


"Donnal Walter" <donnal at donnal.net> wrote in message
news:918bc22f.0210121149.4dc14e0c at posting.google.com...

>     def Add(self, type, name, arg1, arg2):
>         self.__dict__[name] = type(arg1, arg2)
>         self.objectList.append(self.__dict__[name])
> [...]
> 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)

Not if the implementation of instance namespaces is changed, of course :-).

A cleaner way is:
    def Add(self, type, name, arg1, arg2):
        obj = type(arg1, arg2)
        setattr(self, name, obj)
        self.objectList.append(obj)

I think setattr(foo, "bar", baz) is *defined* to have the same effect as
foo.bar = baz (or vice versa or something :-)

You could even have "varargs":
    def Add(self, type, name, *args):
        obj = type(*args)
        ...

> 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?

Not necessarily. But I can think of two issues:
 - Someone reading "type(arg1, arg2)" may get confused, because 'type'
usually means something else. 'type' is maybe practically a keyword in many
people's minds.
 - Someone changing your function might get into trouble when he tries to
use the 'type' builtin, like "assert type(arg1)==Foo" or something.

Builtins like 'list', 'type', 'str', 'repr', 'int' and so on are almost
"pseudo keywords". I.e., they would probably be keywords in many other
languages, but because of Python's very dynamic nature, we have the luxury
of having them as first class objects. I think it is a good rule that this
luxury should not be abused by using the names for something else.


Kind regards,
Bjarke







More information about the Python-list mailing list