Skip to content

Incorrect re-definition of global variables #187

@tomMoral

Description

@tomMoral

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

Script

from cloudpickle import dumps, loads VARIABLE = "uninitialized" def func1(): global VARIABLE print("[func1] global var id{}: {}".format(id(VARIABLE), VARIABLE)) VARIABLE = "initialized" return VARIABLE # Dump and reload the function reloaded_f1 = loads(dumps(func1)) # The function call does not change the value of the global VARIABLE assert reloaded_f1() == "initialized" print(VARIABLE) # Changing the value of VARIABLE does not affect the function VARIABLE = 'test' assert reloaded_f1() == "initialized" # But redumping it changes the value assert loads(dumps(func1))() == "initialized" print(VARIABLE)

Output

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

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.

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