2

Is there any way to print all the local variables without printing them expilictly ?

def some_function(a,b):
    name='mike'
    city='new york'

    #here print all the local variables inside this function?
Ravi
  • 2,778
  • 2
  • 20
  • 32
  • Does this answer your question? [Viewing all defined variables](https://stackoverflow.com/questions/633127/viewing-all-defined-variables) – Countour-Integral Dec 18 '20 at 21:51
  • @Countour-Integral No, my question specific to the function variables. The below answer satisfies my question. – Ravi Dec 18 '20 at 21:54
  • The very first and at least half of the answers there, mention how to get local variables despite the more generilized title. It does indeed answer your question. – Countour-Integral Dec 18 '20 at 21:57

2 Answers2

2

That would be the locals() built-in function

Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>> x = 5
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': 5}

You can filter out the builtins with a list comprehension:

>>> [_ for _ in locals() if not (_.startswith('__') and _.endswith('__'))]
['x']
joedeandev
  • 626
  • 1
  • 6
  • 15
1

If you just want variable names you can use dir() as well:

def some_function(a, b):
    name='Mike'
    city='New York'

    # print all the local variables inside this function?
    print(dir())
some_function('a', 'b')
Yonas Kassa
  • 3,362
  • 1
  • 18
  • 27