-2

The question is as it is in the 'Title', but for the sake of completeness -

Suppose :

>>> a= 23
>>> h ="Liam Neeson"
>>> k ={'a','b','c'}

Are three variables. Then I do a whole bunch of other stuff. And I want to see what variables I have initialised so far, is there a way to do it? Something that will return

[a,h,k].

lightsong
  • 383
  • 1
  • 6
  • 19

2 Answers2

2

If you only want user defined variables, you could use dir and strip out the builtins:

set(dir()) - set(dir(__builtins__)) - {'__builtins__'}

Demo:

>>> a = 23
>>> h = "Liam Neeson"
>>> k = {'a', 'b', 'c'}
>>> set(dir()) - set(dir(__builtins__)) - {'__builtins__'}
{'a', 'h', 'k'}
anon582847382
  • 19,907
  • 5
  • 54
  • 57
1

yes, using the dir() function:

dir([object]) Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

example:

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> a = 1
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a']
yurib
  • 8,043
  • 3
  • 30
  • 55