1

Suppose that you have a program running, and part of the program deals with sets that have been created elsewhere on the program. But you don't know the actual names of the sets, you need to find that out. Is that possible? If so, how?

VannyJ
  • 67
  • 4
  • 9
  • are you asking for `globals()`? – Pavel Feb 24 '17 at 11:54
  • Can you provide some more details on what you're really trying to accomplish? It is possible to use dir() to get a list of variables at the current scope and then do some extra work to go through that list and look for ones of type set, but that won't help if you have non-global sets elsewhere. Alternatively, you could look at creating an InstrumentedSet wrapper (just because it feels Java-y doesn't mean it's wrong) that tracks anytime you create one – Foon Feb 24 '17 at 11:55
  • 1
    Typical XY problem. Please explain your real problem instead. – bruno desthuilliers Feb 24 '17 at 12:18
  • Voting to re-open. This is a perfectly reasonable question. Python does in fact have tool whose principal purpose is to aid debugging be finding the referrers to an object. https://docs.python.org/3/library/gc.html#gc.get_referrers – Raymond Hettinger Mar 19 '17 at 06:58

2 Answers2

0

The solution using built-in globals() and isinstance() functions:

s1 = set([1,2,3])

d = dict(a=1,b=2)

s2 = set([1,2,3])

l = [1,3,3]
s3 = set([1,2,3])

all_vars = globals().copy().items()
for k,v in all_vars:
    if isinstance(v, set):
        print(k)

The output:

s1
s3
s2
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0
a = set()
b = a
c = [set()]

def fun(x):
    print(x)

fun(set())

fun(b)

Now what are "the name" of those sets ?

What I mean here is that your question doesn't make sense, it's just not how Python works. It's a typical XY problem, so please post a question about your real problem, not about what you think is the solution.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118