Get inner function result without interaction of outer function in python - python

I want to get inner function result so i code it like
def main():
def sub():
a = 1
print a
exec main.__code__.co_consts[1]
using above code working successfully but i want to pass the argument to the sub function like...
def main():
def sub(x):
a = x + 1
return a
ans = exec main.__code__.co_consts[1]
print ans
in that problem is i don't know how to pass that x value.
that work must need to exec so that how to pass that x value with exec without interaction of main function

Maybe something like the code below, as suggested by this SO answer
def main():
def sub():
a = x + 1
print a
return a
exec(main.__code__.co_consts[1], {'x': 1} )

Related

How to get return output from another script?

How can i get the output from another script?
My first script to run:
from test2 import *
class Test():
def todo (self):
mult()
addx()
if __name__ == '__main__':
Test().todo()
My second script named (test2.py):
def mult():
x= 2 * 4
print(x)
return x
def addx():
sum = x + 2
print("sum",sum)
Error:
NameError: name 'x' is not defined
In the function addx() you haven't declared x. I believe you want x from mult. So you can do something like this
def addx():
x = mult()
sum = x + 2
print("sum",sum)
You should use the return value of mult, to pass it to your second function addx as a parameter.
def todo (self):
x = mult()
addx(x)
I advise you to read the Python doc section about function : https://docs.python.org/fr/3/tutorial/controlflow.html#defining-functions
In test2.py, you have not defined x
def addx():
sum = x + 2
print("sum",sum)
The problem above is that the computer doesn't know what x is. You could pass it as a parameter:
def addx(x):
sum = x + 2
print("sum", sum)
and change your code to:
from test2 import *
class Test():
def todo(self):
addx(x=mult()) # whatever number you want
if __name__ == '__main__':
Test().todo()

How to call function from list if exists

I have a list of functions and need to call a function, if that function exists in that list. Also, I need to call the function with a string.
I have tried doing something like this:
if "func1" in funcs:
funcs.__getitem__("func1")
but I can't get it right
funcs = [func1, func2, func3]
def func1: return 1
def func2: return 2
def func3: return 3
if "func1" in funcs:
# call func1 since it exists
I expect the output to be 1, but I don't know how to call the function.
Also, this is not a duplicate because I won't call the function from a class.
Found out that I'll just use a dictionary instead. Much easier.
funcs = {"func1": func1, etc..}
def func1(): return 1
def etc..
if "func1" in funcs:
funcs["funcs1"]()
You can also use the class structure and the inspect module which might provide a bit more flexibility:
import inspect
class funcs:
def func1(): return 1
def func2(): return 2
def func3(): return 3
listfuncs = inspect.getmembers(funcs, lambda a:inspect.isfunction(a))
print(listfuncs)
listfuncs will be a list of tuples with function names and object reference.
Just improvising on the answer already provided by #Gwang-Jin Kim.
What happens if you do it this way?
def func1():
return 1
def func2():
return 2
tuple_list = [("func1",func1), ("func2", func2)]
if any([items[0] == "func1" for items in tuple_list]):
print("Do Something")
or this
for key, val in tuple_list:
if key == "func1":
print(val())
Also, it seems like a repeated question of call list of function using list comprehension
Gwang-Jin Kim is right in the fact that Python is interpreted; therefore, you functions needs to be defined before they are called. Now, you need to call a function when the user types the name of that function. It is possible to run the text that the user types with the eval() function; however, that is not recommended, because one cannot be sure of what the user will type in, which could result in unwanted errors.
Instead I recommend that you use a command system, where you call a function based on a predefined name, like shown:
def func1():
print(1)
def func2():
print(2)
while True:
try:
msg = input('Which function would you like to call?: ')
if not msg:
break
if msg.startswith('func1'):
func1()
if msg.startswith('func2'):
func2()
except Exception as e:
print(e)
break
def func1(): return 1
def func2(): return 2
def func3(): return 3
funcs = [func1, func2, func3]
funcs_dict = {f.__name__: f for f in funcs}
funcname = "func1"
funcs_dict[funcname]()
This checks - if functionname is under the functions name in funcs, then executes it!
(One can use dictionaries in Python to avoid if-checkings).
In case, that there are not such a list like funcs given, one has to do it using globals():
if callable(globals()[funcname]):
print(globals()[funcname]())
if callable(eval(funcname)):
print(eval(funcname)())
or:
try:
print(eval(funcname)())
except:
print("No such functionname: {}".format(funcname))
or:
try:
globals()[funcname]()
except:
print("No such functionname: {}".format(funcname))

Access variable of outer function from inner function

I want to use a construct like this, where a function is defined inside of another and can alter a value defined in the outer function:
def function1():
res = []
def function2():
global res
if (possibleToAnswer):
res.append(answer)
else:
function2()
return res
print (("%s") % function1(para))
It doesn't seem to work. I keep getting unbound bug. Any idea about how to get it to work?
Don't use global—it's not in the immediate scope of function2, but it's not global.
def function1():
res = []
def function2():
if (possibleToAnswer):
res.append(answer)
else:
function2()
return res
print (("%s") % function1(para))

How to call an arraylist from a function to another function in python?

Say for example I got the code:
def getRoute(getRouteFile):
getRoutePath = []
routeFile = open(getRouteFile, "r")
for routes in routeFile:
getRoutePath.append(map(ord, routes.split('>')))
return getRoutePath
If I do a function such as which would try and call the items in the getRoutePath array from a function called:
def routeCalculation(getRoute,nodeTable, currentNode):
How do I call it? I tried doing these:
def routeCalculation(getRoute,nodeTable, currentNode):
route = getRoutePath
def routeCalculation(getRoute,nodeTable, currentNode):
route = getRoute[getRouthPath]
And none seem to work. Can anyone help me?
Whenever you declare a variable in a function, when you exit the function, the variable is destroyed. Example:
a = ""
def function():
a = "hello"
b = "hello"
print(a) #prints "hello" because a was declared outside of the function
print(b) #does not print anything
This is called "scope", and if you have a problem understanding it, you should search up a tutorial about it. In order to fix your problem move the code getRoutePath = [] outside of your functions.

Python decorator TypeError 'object is not callable'

I am trying to get myself familiar with decorators.
This is a program I created to do so, but it keeps giving me an TypeError: 'int' object is not callable error, which I don't know how to fix.
#Filename: decorator_practice.py
def add(x):
def add_1():
add_1 = x() + 1
return add_1
def minus(x):
def minus_1():
return x() - 1
return minus_1
def multi(x, times=2):
def multi_2():
return x() * 2
def multi_3():
return x() * 3
def multi_4():
return x() * 4
if times == 2:
return multi_2
elif times == 3:
return multi_3
elif times == 4:
return multi_4
else:
return "Please enter times between 2 and 4"
def create_x():
x = input('Give variable x a value: ')
return x
add(create_x()())
I run this and type: 5
Can anyone help me? Thanks!
Your create_x function returns an integer:
def create_x():
x = input('Give variable x a value: ')
return x
so create_x()() is never going to work.
Part of the problem is that you've used poor parameter names, which is confusing you - you have two xs which refer to two completely different things. Using your add decorator as an example, modify to:
def add(func):
def add_1():
return func() + 1 # you should return from the inner function
return add_1
Now hopefully it is clear that the argument to add should be a function, which is called inside add_1. Therefore you could do:
adder = add(create_x) # don't call create_x yet!
adder() # calling add_1, which calls create_x
which simplifies to:
add(create_x)() # note ordering of parentheses
Note that this could also be written:
#add
def create_x():
...
create_x()
where the syntax #add means create_x = add(create_x).
Once you've mastered simple decorators, note that your multi will not work as you expect - see e.g. python decorators with parameters for creating decorators that take arguments.
You have unnecessary (), change add(create_x()()) to add(create_x()),
and I suggest using x = int(raw_input('Give variable x a value: '))
See the following example:
def add(x):
def add_1():
#add_1 = x() + 1 # remove this line
return x+1
return add_1
def create_x():
x = input('Give variable x a value: ')
return x
b = add(create_x())
print 'answer: ', b()
localhost# python t.py
Give variable x a value: 5
answer: 6

Categories