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?

senderle
  • 125,265
  • 32
  • 201
  • 223
bner341
  • 435
  • 1
  • 6
  • 8
  • 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)` – Yaroslav Surzhikov Sep 17 '17 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. – chepner Sep 17 '17 at 17:31

1 Answers1

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.

Daniel Roseman
  • 541,889
  • 55
  • 754
  • 786