1

I've noticed a strange behaviour in python interpreter when using cross-file imports. The following example of code illustrates this. Class State should be the same because it should be instantiated only once, but printing IDs of it shows that objects actually differ.

Is this a bug or a feature documented somewhere?

Running the following code:

# main.py

print 'Entering Main'
import sys
print 'Importing Actions from Main. Actions is in modules:', 'actions' in sys.modules
import actions

class State (object):
  pass

print 'State ID in Main', id(State)

if __name__ == '__main__':
  print 'OK'
print 'End of Main!'
# actions.py
print 'Entering Actions'

print 'Importing State from Actions'
from main import State

print 'State ID in Actions', id(State)
print 'End of Actions!'

produces the following output:

Entering Main
Importing Actions from Main. Actions is in modules: False
Entering Actions
Importing State from Actions
Entering Main
Importing Actions from Main. Actions is in modules: True
State ID in Main 34782944
End of Main!
State ID in Actions 34782944
End of Actions!
State ID in Main 34817664
OK
End of Main!

Gist URL

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
tosh
  • 19
  • 3
  • 1
    If you also `print State`, you'll see the difference (`` vs. ``). This only happens because of the special `__main__` namespace, so only happens when you're running the script directly. – jonrsharpe Jul 27 '15 at 10:21
  • http://stackoverflow.com/questions/15159854/python-namespace-main-class-not-isinstance-of-package-class – enomad Jul 27 '15 at 10:37
  • Exactly! I thought about it after I posted the message. Could you design your answer as a post so I could mark issue as accepted. – tosh Jul 27 '15 at 11:35

0 Answers0