Reputation: 15204
I was trying to come up with a way to isolate variables that have been defined after a certain point in my code. For this task, I wrote the following:
from copy import deepcopy
beginning = deepcopy(dict(globals())) # getting the current stand
a = 5 # new variable gets defined
# possibly more code with other definitions here
end = {k: v for k, v in dict(globals()).items() if k not in beginning}
Upon printing end
I was expecting to see {'a': 5}
only, but that was not the case. Instead, I got the entire scope all over again.
As a result, it is clear that the if
condition on the dictionary comprehension fails. So I have two questions:
P.S: I am using Python 3.6.1
Upvotes: 2
Views: 61
Reputation: 41228
I get TypeError: can't pickle module objects
when applying deepcopy()
but ignoring that (and doing a shallow copy), you can get your desired output.
I think your conceptual mistake was to forget that beginning
has also been added to the globals()
dict
and needs to be excluded in the if
clause:
>>> beginning = dict(globals())
>>> a = 5
>>> end = {k: v for k, v in dict(globals()).items() if k not in beginning and k != 'beginning'}
>>> end
{'a': 5}
Upvotes: 3