__import__
Heiko Wundram
heikowu at ceosg.de
Sat May 8 05:33:09 EDT 2004
Am Samstag, 8. Mai 2004 10:19 schrieb Ryan Paul:
> "Its ok to use a language
> feature as long as I know what I am doing."
Hmm... If you need to override a builtin, and do not duplicate the original
behaviour exactly (that's pretty much what the op wanted to do, anyway, if
you need to override a builtin, you're not into duplicating the original
behaviour), then you always create a can of worms whenever you use a
different package.
Say, I use: __import__("blah",{},{}), and my library expects __import__ to
throw an error in case blah can't be found, to check whether my functionality
is there or not. What the op wanted to do is to replace this check with some
deep magic, probably returning a package instead when the actual import
fails. What is my program expected to do? The import succeeds, but the
package which was actually returned isn't usable, because it doesn't
duplicate what I expect __import__("blah") to return.
It's always much, much cleaner to not override the builtin, but to create a
new method, which has the behaviour you want, and then to use that one
throughout your package. That way each programmer can rely on the fact that
the builtins work as they are specified in the language reference, and can be
sure that his/her module also works on a different machine/with different
modules, just because the underlying Python is the same.
I've had to recode a project someone else wrote, and he heavily made use of
such deep magic to create something which was a bit shorter overall, but
which was much more difficult to maintain for me later on just because
plugging in some other modules to extend the functionality simply was not
possible anymore. He also overrode __import__ to return some dummy-module in
case the one being imported wasn't found, and did even more black-magic
checks to see where the call came from using the stack-trace, and then tested
whether it was okay to return a dummy module or not. This is a maintenance
nightmare...
Heiko.
More information about the Python-list
mailing list