confused by isinstance()

Alex Martelli aleax at
Fri Feb 1 23:22:35 CET 2002

Francois Petitjean wrote:
> Where in the documentation is explained what means "Importing a module
> executes each line in the file". 

Language reference manual.

> The lines are syntaxically checked, sure,
> but most of the work is not done at this stage:

No, but every top-level statement is still executed.

> def curve(x):
>     return return 10.0*math.sin(x)/x
> conversion to byte code.

def is the top-level statement, and it's executed on import.

>>Every time you execute a class statement, even if the class name is the
>>same, you create a new class.
> This is the crux of the problem, but after the first import, it seems that
> successive import of a module give the same class, due to the sys.module
> caching. Right?

Only if the imports use the same name.  In your case, you were
importing the same module as __main__ (implicitly) and foo
(explicitly).  sys.modules is checked with the modulename as
the key, after all.  (You may also choose to import with various
modulenames -- check standard module imp for that, although
you rarely need this).  Note that "import x as y" is not an example:
the module is imported (and set/checked in sys.modules) with
a name 'x', it's only the local binding that uses 'y' here.

> So, if I want to be on the safe side and to test a module Foo as it
> appears from outside, I can begin the __main__ part with import Foo. In
> this case, instanciation is of the form x = Foo.Foo(), all is good except
> for the doubling of the memory to store the class.

If all the top-level statements in the modules are OK to execute
twice, yes.  But if the top-level does e.g. an append to a file, you'll
find two appends using this approach.


More information about the Python-list mailing list