• Re: Variable scope inside and outside functions

    From Stefan Ram@21:1/5 to Jacob Kruger on Tue Mar 5 18:46:31 2024
    Jacob Kruger <[email protected]> wrote or quoted:
    l_servers = []
    ...
        global l_servers
    That should, in theory, mean that if I assign a value to that variable
    inside one of the functions, it should reflect globally?

    Yes.

    l =[ 1, 2, 3 ]

    def f():
    global l
    l =[ 2, 3, 4 ]

    f()

    print( l )
    # [2, 3, 4]

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Stefan Ram@21:1/5 to Grant Edwards on Tue Mar 5 23:12:24 2024
    Grant Edwards <[email protected]> wrote or quoted:
    Python Global variables are those which are not defined inside
    any function and have a global scope whereas Python local
    variables are those which are defined inside a function and their
    scope is limited to that function only.
    Since "define" (in this context) isn't a term of art in Python, and

    |If a local variable is defined in a block,
    The Python Language Reference, Release 3.13.0a0,
    4.2.2 Resolution of names, p1

    |checking the module’s namespace for a variable named __all__;
    |if defined, it must be a sequence of strings
    ibid., 7.11

    |class variable A variable defined in a class
    ibid., Appendix A

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Stefan Ram@21:1/5 to Jacob Kruger on Wed Mar 6 13:17:45 2024
    Jacob Kruger <[email protected]> writes: if you execute
    do_it function, it will print out the new value assigned to the
    dt_expiry variable inside that function, but if you then again check the >value of the dt_expiry variable afterwards, it's reverted to the 1970... >value?

    I can only guess that after "do_it" you might have inadvertently
    restarted the interpreter.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Stefan Ram@21:1/5 to Jacob Kruger on Wed Mar 6 16:40:26 2024
    Jacob Kruger <[email protected]> wrote or quoted:
    from scoping2 import *

    Now, "dt_expiry" exists in /two/ modules: In "scoping2" and in the
    current module (as a copy). To avoid this, "import scoping2" instead.

    print(dt_expiry)
    1970-01-01 00:00:00+00:00
    do_it()
    2024-03-06 18:12

    This changes the variable "dt_expiry" in "scoping2", but not the
    copy (also named "dt_expiry") in the current module.

    print(dt_expiry)
    1970-01-01 00:00:00+00:00

    This prints "dt_expiry" from the current module, not from "scoping2".

    To avoid this, replace "from scoping2 import *" by "import scoping2"
    and replace the "dt_expiry" in the two print statements by
    "scoping2.dt_expiry".

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)