1

I checked some answers like this, but I have another question about which attributes get imported from a module in python.

For example, I have a module temp9.py:

a=10
b=20
print('a={0}, b={1}'.format(a,b))
def t9outer():

    print('in imported module')
    def t9inner():
        print('inner function')

Then I import this module like so: import temp9. If I get the attributes of the imported file using this command:

list(filter(lambda x: not x.startswith('__'),dir(temp9)))

I get this output:

['a', 'b', 't9outer']

My questions are

  • a and b are global only in the scope of temp9, not across the modules (as the above answer says), so how does it get exported?

  • Why was t9inner() not imported even though it is enclosed by t9outer(), which gets imported?

2
  • 1
    a,b are actually gloabal in scope of temp9. If you try to access them in your main module - you will get NameError. But, you can access them via temp9.a or temp9.b. And t9inner in not listed in dir of module, because it's in scope of t9outer. You can check this via dir(temp9.t9outer) Commented Sep 17, 2017 at 17:24
  • t9inner doesn't exist at all until you actually call t9outer, and even then the name is only in scope in the body of the function. You can think of a def statement as a souped-up assignment statement. Commented Sep 17, 2017 at 17:31

1 Answer 1

4

The answer is the same for both questions. Everything defined at module level is imported; anything not defined at module level is not imported.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.