Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print all variables and their values [duplicate]

Tags:

python

This question has been asked quite a bit, and I've tried each solution I come across, but haven't had any success. I'm trying to print out every variable and its value using the following two lines.

for name, value in globals():
    print(name, value)

This gives an error: Too many values to unpack When I run:

for name in globals():
    print(name)

I only get the names of the variables. Any help would be appreciated.

like image 823
asheets Avatar asked Oct 01 '17 19:10

asheets


1 Answers

globals() returns a dict - so, to iterate through a dict's key/value pairs, you call it's items() method:

dog = 'cat'
>>> for name, value in globals().items():
...     print(name, value)
... 
('__builtins__', <module '__builtin__' (built-in)>)
('__name__', '__main__')
('dog', 'cat')
('__doc__', None)
('__package__', None)
>>> 

This is explained within the docs for Data Structures, available here!

Python 3 version:

for name, value in globals().copy().items():
    print(name, value)

if we do not copy the output globals functions then there will be RuntimeError.

Also if there are list and dictionaries in the output of some variable then use deepcopy() instead of copy()

for name, value in globals().deepcopy().items():
    print(name, value)
like image 66
n1c9 Avatar answered Sep 28 '22 15:09

n1c9