Search code examples
pythonros

How to use variables in other .py files


I have file A.py in a package with a class and a list as class attribute or class variable. File A run a loop to update value to that list. How can I get the list and all changes to file B.py (in another package).


Solution

  • When using only 'class attributes', the values are static, a simple 'import' should work.

    For example, proj/package1/A.py:

    class A:
        attr1 = "foo"
        attr2 = "bar"
    

    Create file __init__.py in all directories: current, package1, package2

    Import A from proj dir in proj/B.py:

    from package1.A import *
    print(A.attr1)
    print(A.attr2)
    

    Import A from non-parent dir, eg. proj/package2/B.py

    import sys
    sys.path.append("package1") # Run programme in `proj` dir
    
    from A import *
    print(A.attr1)
    print(A.attr2)