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
Related
This question already has answers here:
exec() not working inside function python3.x
(5 answers)
Closed 1 year ago.
My question regards the following code examples: Example 1 works fine, while example 2 fails.
# example 1
string_one = 'greeting_one = "hello"'
exec(string_one)
print(greeting_one)
# example 2
def example_function():
string_two = 'greeting_two = "hi"'
exec(string_two)
print(greeting_two)
example_function()
Example 1 creates the variables in the global scope and example 2 should create the variables in the local scope, otherwise those two should be identical (?). Instead example 2 gives the following error: name 'greeting_two' is not defined. Why is exec() not working as indented in example 2?
Pass the current local scope to the function and use that as the local dictionary for exec().
# example 2
def example_function(loc):
string_two = 'greeting_two = "hi"'
exec(string_two, loc)
print(greeting_two)
example_function(locals())
Read more here
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 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 Script returns unintended "None" after execution of a function [duplicate]
(3 answers)
Closed 4 years ago.
I'm practising with unit test module.
I have this simple code. It is a function that joins strings so that I can get this result: "City, Country"
def city_country(city_name, country_name):
"""Simple code that prints City, Country"""
print(city_name.title() + ", " country_name.title())
When I run it, the function works OK.
I wrote a class to test the code with unit tests, and I got an error.
I noticed that when I assign the function to a variable, like this :
city_country_var = city_country('Punto Fijo', 'Venezuela')
And then import it to the TestClass(or somewhere else), print it, this is the result :
Punto Fijo, Venezuela
None
I don't know how to handle it or why is it caused, since it's the same function that worked fine earlier by itself. But it only gives me that result if I import the function to another file. Can I get some advice about why does it happen and how to solve it?
your city_country function does not return any value. It just prints the result and returns None (by default).
Apply those changes and your variable should have the string value you desire:
def city_country(city_name, country_name):
"""Simple code that prints City, Country"""
result = (city_name.title() + ", " country_name.title())
print(result)
return result
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.