Print all variables and their values [duplicate]

2024/10/13 9:16:14

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.

Answer

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)
https://en.xdnf.cn/q/69546.html

Related Q&A

How to emulate multiprocessing.Pool.map() in AWS Lambda?

Python on AWS Lambda does not support multiprocessing.Pool.map(), as documented in this other question. Please note that the other question was asking why it doesnt work. This question is different, Im…

Tkinter overrideredirect no longer receiving event bindings

I have a tinter Toplevel window that I want to come up without a frame or a titlebar and slightly transparent, and then solid when the mouse moves over the window. To do this I am using both Toplevel.…

Reusing Tensorflow session in multiple threads causes crash

Background: I have some complex reinforcement learning algorithm that I want to run in multiple threads. ProblemWhen trying to call sess.run in a thread I get the following error message:RuntimeError: …

Conditional column arithmetic in pandas dataframe

I have a pandas dataframe with the following structure:import numpy as np import pandas as pd myData = pd.DataFrame({x: [1.2,2.4,5.3,2.3,4.1], y: [6.7,7.5,8.1,5.3,8.3], condition:[1,1,np.nan,np.nan,1],…

Need some assistance with Python threading/queue

import threading import Queue import urllib2 import timeclass ThreadURL(threading.Thread):def __init__(self, queue):threading.Thread.__init__(self)self.queue = queuedef run(self):while True:host = self…

Python redirect (with delay)

So I have this python page running on flask. It works fine until I want to have a redirect. @app.route("/last_visit") def check_last_watered():templateData = template(text = water.get_last_wa…

Python Selenium. How to use driver.set_page_load_timeout() properly?

from selenium import webdriverdriver = webdriver.Chrome() driver.set_page_load_timeout(7)def urlOpen(url):try:driver.get(url)print driver.current_urlexcept:returnThen I have URL lists and call above me…

Editing both sides of M2M in Admin Page

First Ill lay out what Im trying to achieve in case theres a different way to go about it!I want to be able to edit both sides of an M2M relationship (preferably on the admin page although if needs be …

unstacking shift data (start and end time) into hourly data

I have a df as follows which shows when a person started a shift, ended a shift, the amount of hours and the date worked. Business_Date Number PayTimeStart PayTimeEnd Hours 0 2019-05-24 1…

Tensorflow model prediction is slow

I have a TensorFlow model with a single Dense layer: model = tf.keras.Sequential([tf.keras.layers.Dense(2)]) model.build(input_shape=(None, None, 25))I construct a single input vector in float32: np_ve…