Skip to content

Incorrect re-definition of global variables #187

Description

@tomMoral

The global variable are not correctly handeled in the __main__ module as they do not remain global.

Script

fromcloudpickleimportdumps, loadsVARIABLE="uninitialized"deffunc1():
globalVARIABLEprint("[func1] global var id{}: {}".format(id(VARIABLE), VARIABLE))
VARIABLE="initialized"returnVARIABLE# Dump and reload the functionreloaded_f1=loads(dumps(func1))
# The function call does not change the value of the global VARIABLEassertreloaded_f1() =="initialized"print(VARIABLE)
# Changing the value of VARIABLE does not affect the functionVARIABLE='test'assertreloaded_f1() =="initialized"# But redumping it changes the valueassertloads(dumps(func1))() =="initialized"print(VARIABLE)

Output

[func1] global var id140197480377584: uninitialized
uninitialized
[func1] global var id140197483839984: initialized
[func1] global var id140197480295592: testtest

I think a way to avoid this is to pass the global variable to _fill_function and use globals():

  • If the global variable is already present in globals, do not do anything.
  • If it is not present, add it with the given value.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions