This question already has answers here:
How to print original variable's name in Python after it was returned from a function?
(13 answers)
Simpler way to create dictionary of separate variables?
(27 answers)
Closed 8 years ago.
For Python 2.7 I have a little utility for debugging:
def printvar(label, var):
print "%s:\n%s" % (label, pformat(var))
Often I call it like printvar("foo", foo).
Is it possible to simplify that a tiny bit and only pass in the variable, like printvar(foo), but still have it print the name of the variable? Using introspection or something?
You can't do that, but you can approximate the reverse: pass in only the label, and have it grab the actual value. Here's a quick version:
def printvar(label):
for frame in inspect.getouterframes(inspect.currentframe())[1:]:
local_vars = frame[0].f_locals
if label in local_vars:
print "%s:\n%s" % (label, frame[0].f_locals[label])
return
raise NameError("No such variable")
Then you can do this:
def foo():
x = 2
printvar('x')
>>> foo()
x:
2
This is, of course, very hacky business: the code looks through the local-variable namespaces of every stack frame in its call chain. Normally this kind of trickery is to be avoided, but for debugging purposes it can be useful in a pinch.
Related
This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 months ago.
This is a program to make the text print with each word beginning with a capital letter no matter how the input is.
So my question is why do we use return here :
def format_name(f_name, l_name):
formatted_f_name = f_name.title()
formatted_l_name = l_name.title()
return f"{formatted_f_name}{formatted_l_name}"
print(format_name("ABcDeF", "Xy"))
when I could just do this :
def format_name(f_name, l_name):
formatted_f_name = f_name.title()
formatted_l_name = l_name.title()
print(f"{formatted_f_name}{formatted_l_name}")
format_name("ABcDeF", "Xy")
What scenarios would it be really useful in?
The main reason that the return keyword is used is so that the value of the function can be stored for later, rather than just printing it out and losing it.
e.g.
def someFunction(a,b):
return(a+b/3)
a=someFunction(1,2)
This means that what the function does can be stored for later.
For example:
print(a)
print(a/2)
print(a+3)
return statements don't just replace print, they allow you to do a load of other things by storing the end value (the value inside return) in a variable.
print()ing in a function, however, only allows us to print the variable to the console, not allowing us to do anything or use the value that it prints.
e.g.
def someFunction(a,b):
print(a+b/3)
a=someFunction(1,2)
print(a)
Although the function already prints the value off for you, the variable I assigned it to shows that the function is practically useless unless you run it a bunch of times. a will print off None in the case above.
Hope that was helpful.
This question already has an answer here:
exec() and variable scope [duplicate]
(1 answer)
Closed 1 year ago.
I'm writing a library that involves codegen, and I'd like to test that the code I'm generating is doing what I expect it to. I want to generate the code, exec it, and then verify that the result is what I expect it to be. However, I'm finding that when I do this in my test functions, the variable I set in the generated code aren't visible. For instance, this works perfectly:
exec('a = 1')
print(a)
However, this fails with a NameError:
def demo():
exec('b = 2')
print(b)
demo()
What gives?
Sadly from my understanding, you cannot use exec like that in a function. Instead you can store this in a dictionary as shown below.
def demo():
varDict = {}
exec("b=2", varDict)
print(varDict["b"])
demo()
output
2
This question already has answers here:
Calling a function of a module by using its name (a string)
(18 answers)
Closed 2 years ago.
I'm really new to Python but I'm trying to do something definitely above my skill level.
Is it possible to calla a function though a variable? For example,
def one():
print("this is a function")
progress = "one"
progress()
with the intention of calling the function "one()".
Is this possible?
Just take off the double quotes around "one" and you should be good.
def one():
print("this is a function")
progress = one
progress()
This question already has answers here:
Assigning a function to a variable
(7 answers)
Closed 4 years ago.
I'm trying to activate a function which is stored inside a variable.
I've tried to use "lambda:" like this:
def test():
print("this works")
var = test()
lambda: var
It doesn't work. Is there any way to do that without doing anything complex? If not I don't mind hearing the complex way.
Edit:
When I posted this I meant that I wanted parameters in the function for example if you use:
def test(thing):
print(thing)
var = test
var()
Sorry for the confusion.
You use the parentheses to call the function. When you assign, you don't need the parentheses.
>>> def test():
... print("this works")
...
>>> var = test
>>> var()
this works
This question already has answers here:
Python string to attribute
(3 answers)
Calling a function of a module by using its name (a string)
(18 answers)
Closed 5 years ago.
I have a file allthetests.py with a number of small functions defined like this:
def test1():
##do some stuff
if (everything_is_awesome):
return({"status":PASS, "data":"all the data"})
def test2():
##do some different stuff
if (everything_is_bad):
return({"status":FAIL, "data":"no data"})
Then I have another bunch of files which are descriptions of nodes and get imported as dicts like this
{"node_type":"action",
"title":"things",
"test":"test2"}
Finally I have a third file main.py which is in charge of everything.
In this third file, I want to import allthetests.py, load the node descriptions and then call allthetests.test1() or allthetests.test2() or whatever that case is. I imagine it might look something like this but I'm not really sure where to go from here...
import allthetests
cur_node = load_node()
## Doesn't work but...
return_val = allthetests.cur_node['test']()