[Python] How to make script-level variables private to the script

Discussão em 'Python' iniciado por Stack, Março 7, 2025.

  1. Stack

    Stack Membro Participativo

    Is it possible to declare a global variable that is invisible to the importing script?

    For example, in script a.py I have a variable var_a that is accessible to any function in a.py. However, in script b.py that imports a.py, I want var_a to be inaccessible.

    (A somewhat similar concept to C's static module variables)

    In a.py:

    var_a = "hello"

    print("In script a.py:", var_a)


    In b.py:

    from a import var_a

    print("In script b.py:", var_a)


    Testing:

    $ python3 b.py
    In script a.py: hello
    In script b.py: hello


    I would like to get an error when referencing var_a from b.py.

    Continue reading...

Compartilhe esta Página