Ma0
Ma0

Reputation: 15204

How to get newly defined variables

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:

  1. What am I doing wrong?
  2. How can my desired result be achieved?

P.S: I am using Python 3.6.1

Upvotes: 2

Views: 61

Answers (1)

Chris_Rands
Chris_Rands

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

Related Questions