cloudpipe / cloudpickle

Extended pickling support for Python objects
Other
1.64k stars 167 forks source link

Unable to reference global variables in serialized functions #452

Open ryanthompson591 opened 2 years ago

ryanthompson591 commented 2 years ago

When pickling a function that references a global variable, the global variable is no longer referenced.


import cloudpickle

global x
x = 123

def increment_x():
    global x
    x += 1
    return x

copy_of_increment_x = cloudpickle.loads(cloudpickle.dumps(increment_x))

print('Expecting 124 - got ' + str(increment_x()))
print('Expecting 125 - got ' + str(copy_of_increment_x()))

The following will print Expecting 124 - got 124 Expecting 125 - got 124

Is there a way to reference globals?

tvalentyn commented 2 years ago

cc: @ogrisel - does this sound like a bug to you or there are some reasons to consider this 'WAI'?