0

Can't find anything about this issue online. I have run into some unexpected state issues after using sys.path.append().

I have a Python 3.9 project structured like so:

│ some_class.py
│  
└─submodule
    │ 
    └─some_folder
       │
       └─ shared.py
       │
       └─ some_other_class.py

The submodule folder contains another project (git repo) inside my own project. I want it to remain immutable, so I can easily pull/integrate future changes (and do the same with other submodules in the project). This means not changing anything (including imports) in any files in submodule.

shared.py contains a variable shared_variable = None and some_other_class.py looks like this:

import folder.shared as shared


def some_function():
    print('some_other_class output:')
    print(shared.shared_variable)

some_class.py needs to access submodule. Owing to the requirements stated above (immutability of files in submodule), I use sys.path.append("submodule") to make my program run without changing imports in submodule. some_class.py looks like this:

import sys

sys.path.append("submodule")

from submodule.folder import shared
from submodule.folder.some_other_class import some_function

if __name__ == '__main__':
    shared.shared_variable = 'test'
    print('some_class output:')
    print(shared.shared_variable)
    some_function()

When I run some_class.py the output is this:

some_class output:
test
some_other_class output:
None

How come the output in some_other_class is None? Why isn't there shared state? Is there a workaround for this issue?

Thanks

Ben123
  • 335
  • 2
  • 11

0 Answers0