Question

I had assumed that in Python if I do some

class A:
    print("hi")

this "hi" would only ever be printed more than once if I explicitly deleted A with some del A

In my slightly bigger project I have this code (names changed):

class A(ISomething):
    print(threading.current_thread())
    try:
        A.MY_DICT  # yeah, this should never ever result in anything but an error but neither should this code be run twice
        print(A.MY_DICT)
    except NameError:
        print("A.MY_DICT unknown")
    MY_DICT = {}

and it produces this output:

$ python main.py 
<_MainThread(MainThread, started 140438561298240)>
A.MY_DICT unknown
<_MainThread(MainThread, started 140438561298240)>
A.MY_DICT unknown

so on the same thread the same class level code gets executed twice. How is that possible when I never del A? The code had worked before but I don't have commits to narrow down the change that broke it.

The same code with MY_DICT instead of A.MY_DICT fails equally and as PyDev already at time of writing tells me that this will not work, I am pretty confident that there's something fishy going on.

Was it helpful?

Solution

You are probably importing the file under different names, or running it as both the __main__ file and importing it.

When Python runs your script (the file named on the command line) it gives it the name __main__, which is a namespace stored under sys.modules. But if you then import that same file using an import statement, it'll be run again and the resulting namespace is stored under the module name.

Thus, python main.py where main.py includes an import main statement or imports other code that then in turn imports main again will result in all the code in main.py to be run twice.

Another option is that you are importing the module twice under different full names; both as part of a package and as a stand-alone module. This can happen when both the directory that contains the package and the package itself are listed on your sys.path module search path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top