How to get variable but not call function - python

i'm trying to get the value from an inside function func2, to put it outside without calling func1 and func2. Here is my program:
def func1():
def func2(x, y, z):
# global str
str = "Xin chao`"
# func2()
#func1()
print("Result:", str)

If you don't call the functions, that variable doesn't exists. You could declare it global but it will not take the value Xin chao if you don't call those functions

Related

Scope of variables in nested functions

Code extract is below, I am trying to modify a variable in a nested function, I started out by practising modifying in a normal function and using the keyword 'global', however in a nested function I can only make it work by putting in global (highlighted in comment), but by doing this I am expanding the scope of the 'y' var outside the function bar, to the main program which is not what I want.
I only want the inner function foo to be able to see and modify 'y' but I do not want to make 'y' available to the main program.
Note I have already seen this post Using a global variable inside a function nested in a function in Python, however the question remains.
Thank you.
# accessing x outside scope is okay
x = 5
def bar():
print(x)
bar()
# modifying x outside scope needs global
x = 5
def bar():
global x
x = x+5
print(x)
# now original reference has been changed as well.
bar()
print(x)
# scope within nested functions
def bar():
global y ## why is this needed?
y = 5
print(f'y before foo called (): {y}')
def foo():
global y
y = y + 1
print(f'y in foo called (): {y}')
foo()
print(f'y after foo called (): {y}')
bar()
print(f'y outside function foo called (): {y}')
Your solution works because global y makes y global. It is now available in all functions, including in nested functions. Instead, you probably want to declare nonlocal y inside foo() and remove all the global y declarations. This allows you to assign a value to y in the nested scope without exposing it to other functions.

Calling function from another function

When I call func1 from func2, I get an error. Why is this occurring and how to access the returned dictionary d in func1 from func2?
func1()
NameError: name 'func1' is not defined
class ABC():
def func1(self, a):
d = {}
###do something with a
###return ending dictionary d
return d
def func2(self):
###Retrieve returned dictionary d from func1 and use
func1()
d['key'] = value
func1 and func2 are instance methods of ABC objects. You need to call them from the instance of such object.
In your case, one such instance is self, first parameter of both functions.
Thus, self.func1() will work.
Use self.func1() to call the function inside your class.

creating function object with conditional statement before calling

I have defined two functions(fun1 and fun2), which return some values and I call one of these functions in fun3. I can do if condition inside for loop but is there a way that the function can be chosen before. As shown here. Or is there any other approach?
def fun1(a1,b1)
def fun2(a1,b1)
def fun3(a1,b1,some_para):
if some_para:
sel_func = fun1()
else:
sel_func = fun2()
for Loop:
sel_func(a1,b1)
Functions are objects. Just assign the function instead of calling it. Using your example:
def fun3(a1, b1, some_para):
sel_func = fun1 if some_para else fun2
for Loop:
sel_func(a1, b1)
def fun1(a1,b1)
def fun2(a1,b1)
def fun3(a1,b1,some_para = None):
sel_func = fun1 if some_para else fun2
for Loop:
sel_func(a1,b1)
use some_para =None in function declaration, when you call this function you always need to pass the argument to it and only fun1 will run every time if you don't pass any value an attribute error will occur. if none uses and no value passed fun2 will execute else fun1 will.
You can pass the function as a parameter outside so it is easier to read:
def fun3(a1, b1, sel_func):
for Loop:
sel_func(a1, b1)
# call fun3 with whatever funtion you need in each momment
fun3(a, b, fun1)
fun3(a, b, fun2)

A function that calls X function

I want to basically turn a list element into a function with
the do function. This way any pre-written funcction i can call by just use a
do(list[x]).
What im trying to do is a function that takes away the quotes of a list element and then executes the function that is in that list element.
def func():
print "python"
def func1():
print "is"
def func2():
print "awesome"
def do(fun):
fun()
#I think the problem is here
funs = ['func()','func1()','func2()']
print ''.join(funs[0])
do(''.join(funs[0]))
Edit:
What im trying to do is a function that takes away the quotes of a
list element and then executes the function that is in that list
element
You don't need the extra functions, and you don't need to turn them into a string either:
def func():
print "python"
def func1():
print "is"
def func2():
print "awesome"
funcs = [func, func1, func2]
for function in funcs:
function()
Well, it basically works like this. Note that the list contains the functions themselves, not a string.
def func():
print "python"
def func1():
print "is"
def func2():
print "awesome"
def do(fun):
fun()
funcs = [func, func1, func2]
for function in funcs:
do(function)
Output:
python
is
awesome
EDIT: If you do want the list to contain the functions' names as strings, use eval():
funcs = ['func', 'func1', 'func2']
for function in funcs:
do(eval(function))
If you really want to execute arbitrarily named functions from a list of names in the current global/module scope then this will do:
NB: This does NOT use the potentially unsafe and dangerous eval():
Example:
def func():
return "python"
def func1():
return "is"
def func2():
return "awesome"
def do(func_name, *args, **kwargs):
f = globals().get(func_name, lambda : None)
if callable(f):
return f(*args, **kwargs)
funs = ["func", "func1", "func2"]
print "".join(funs[0])
print "".join(map(do, funs))
Output:
$ python foo.py
func
pythonisawesome
You can also individually call "named" functions:
>>> do(funs[0])
python
Note the implementation of do(). This could also be applied more generically on objects and other modules too swapping out globals() lookups.
As the people above have said the best way is to define a dictionary of functions, as functions are objects in python this is possible
def One():
pass
def Two():
pass
functions = {"ONE":One, "TWO":Two}
You can then call it like this:
functions[input]()
If you want to give true control to the user (And I DO NOT recommend doing this) you could use the eval function.
eval(input+"()")

Shuffling in python

I'm trying to shuffle an array of functions in python. My code goes like this:
import random
def func1():
...
def func2():
...
def func3():
...
x=[func1,func2,func3]
y=random.shuffle(x)
And I think it might be working, the thing is that I don't know how to call the functions after I shuffle the array!
if I write "y" after the last line, it doesn't do anything!
Thanks
Firstly, random.shuffle() shuffles the list in place. It does not return the shuffled list, so y = None. That is why it does nothing when you type y.
To call each function, you can loop through x and call each function like so:
for function in x:
function() # The parentheses call the function
Lastly, your functions actually produce a SyntaxError. If you want them to do nothing, add pass at the end of them. pass does absolutely nothing and is put where python expects something.
So altogether:
def func1():
pass
def func2():
pass
def func3():
pass
x = [func1, func2, func3]
random.shuffle(x)
for function in x:
function()

Categories

Resources