Overriding variables used by base classes

Hung Jung Lu hungjunglu at yahoo.com
Tue Nov 18 08:03:03 EST 2003


google_mail at aristoweb.net (Corey Lubin) wrote in message news:<a64176a.0311172341.43219a82 at posting.google.com>...
> 
> First of all, I wanted my tainted module to completely mimic the
> interface of the original module. Importing in the style that you have
> would not do so, as all names other than "Tainted" would have to be
> prefixed by "original". 

OK, I understand your next point. But let me comment on this first
point, unrelated to the next point. In general, it's a better practice
to avoid the 'from ... import *' syntax, since it makes your code
harder to read: when you see a name inside your module, you are not
sure whether it comes from somewhere else, especially if you have
several 'from ... import *' statements. This recommendation is common.
To give an example: in the past wxPython's examples where filled with
'from' statements, but nowadays more and more people are using
straight 'import' statements, and explicitly type 'wx.' prefix to
module attributes. It is more work, for sure, but if really necessary,
you can (a) use the 'import ... as ...' syntax, (b) if something is
repeatedly used, you can use an alias name, just use the statement
'alias = mymodule.myattribute'.

> My second reason for not following that path was that I had the
> impression that a particular module can only be imported once; any
> further imports of the same module would just be implemented by
> binding new names to the first copy of that module. 

That is correct.

> To further expand upon my concerns raised in the last paragraph, I
> want to have the choice to use either or both of tainted.Tainted and
> original.Original; and when I use them I want them to have distinct
> behaviour. 

Hmm... for your purpose, it may be easier to use the exec statement,
after all.

f = open('foreign_module.py')
module_code = f.read().strip()
f.close()
exec module_code

Whatever asset in the foreign module now becomes part of your module,
as a fresh copy. I would like to point out that this is not a common
approach. Python allows you to do many things. But some approaches
have more side effects than others. For instance, in the above code,
your program will now depend on the module file. This is not a problem
when you are just using Python scripts. But if one day you decide to
package your program into an executable and ship it to other people,
e.g. by using py2exe, this approach would be kind of bad, since you
will also have to ship the foreign module script, or ship its compiled
code, or use some other ways of hacking.

regards,

Hung Jung




More information about the Python-list mailing list