Imported modules become None when running a function

后端 未结 1 1220
无人共我
无人共我 2020-12-10 06:18

Update: some more debugging info at the bottom of this post, which reveals something very screwy in the python state.

I have a module which imports,

相关标签:
1条回答
  • 2020-12-10 06:58

    This happens to a function in an imported module that is still executing after that module is garbage collected.

    Since your code isn't enough to reproduce the issue, here's a simplified example that shows the behaviour. Create a file containing the following and import it either from the Python command line or from another file. It doesn't work if you just run it at the top level.

    import sys
    import threading
    
    x = "foo"
    
    def run():
        while True:
            print "%s %s\n" % (sys, x)
    
    threading.Thread(target = run).start()
    sys.stdin.readline()
    

    Running it:

    $ python
    >>> import evil_threading
    <module 'sys' (built-in)> foo
    
    <module 'sys' (built-in)> foo
    ... press Ctrl-C
    None None
    
    None None
    ... press Ctrl-\ to kill the Python interpreter
    

    During Python shutdown, modules are set to None. This is an obscure Python behaviour that was removed in 3.4. In this example, terminating the main thread results in shutdown, but the other thread is still running, so it sees the modules as None.

    There is a simpler example from here which does the same thing by deleting the module reference directly from sys.modules.

    import sys
    print sys
    del sys.modules['__main__']
    print sys
    
    0 讨论(0)
提交回复
热议问题