1

I have two Python scripts, one testclass.py:

import numpy
zz = numpy

class Something(object):
    def __init__(self):
        self.xp = zz

and one testscript.py:

from testclass import Something
x = Something()
print(x.xp)

I expected testscript.py to throw an error because I thought that testscript only imports the class Something (with its __init__ method), and not the global variable zz. So, given this bevahiour, my question is, when importing from a module, does Python "run" everything in the module file?

1 Answer 1

2

Yes. When you execute:

from testclass import Something

It has the same effect as:

import testclass
Something = testclass.Something

More generally, the Python interpreter can't know beforehand what objects your module exposes (unless you explicitly name them in __all__). For an extreme case, consider the following:

a.py:

import random

if random.random() > 0.5:
    class Foo(object):
        pass
else:
    class Bar(object):
        pass

Running from a import Foo has a 50% chance of failing because the a module object may or may not have a Foo attribute.

Sign up to request clarification or add additional context in comments.

3 Comments

I like the idea of defining random stuff in a module deep in your project. Preferably keeping the same name, but a different MRO, would make for fun times.
Will executing from a import Foo multiple times increase/decrease the chance of failing? Or will the defined class remain the same during the process after the first import?
@ZachGates: The module object is cached in sys.modules after it's first imported.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.