abusing __builtins__

Tim Peters tim.one at home.com
Sun Feb 25 18:08:35 EST 2001

[Vassilis Virvilis]
> In python 1.5.2 (and possible to any future python) is possible to set a
> global variable shared by all modules simply by doing:
> setattr(__builtins__, 'GlobalVariable', GlobalVariable)
> without the need to import anything.


> Not being an experienced python programmer I would like ot hear some
> arguments on whether this is considered abuse of the language or not.
> Should it be avoided?  Are there any hidden pitfalls? except from the
> obvious one that I should not have global variables in the first place.

The language doesn't guarantee this will always work, so it's certainly

Looking up builtins is slower than looking up module globals (a module's
global dict is always searched before the builtin dict).

The language may someday make "GlobalVariable" the name of its own builtin,
and then your code won't work correctly if you either try to use the new
builtin or call any other module that does (incl. without limitation std
library modules).

People other than you will be unable to understand your code regardless,
because GlobalVariable will look to them like an unbound variable (i.e.,
nobody else uses this trick, so nobody else will recognize the usage

Introspective tools won't think to look in the builtins either (again
because nobody else etc).

i-wouldn't-let-any-of-that-stop-me-though<wink>-ly y'rs  - tim

More information about the Python-list mailing list