This is my nested functions code
def get_id():
for i in range(1,100):
pass
return i
def get_id_mysql(x):
print(x)
variable = get_id()
get_id_mysql(variable)
this function get_id return ( output : 1 ) and loop stop.. how can I hand over full loop? I mean 1,2,3..99
I Found solutions
def get_id():
t = []
for i in range(1,100):
t.append(i)
return t
def get_id_mysql(x):
for i in x:
print(i)
variable = get_id()
get_id_mysql(variable)
def outer_function(): # this is the outer most function
print("I am outer")
def inner_func(): # inner function
print("I am inner")
def inner_inner_func(): # inside the inner function
print("I m inner inner")
def inner_inner_func_2(): #inside the child of inner child
print("I a inner inner 2")
return inner_inner_func_2
return inner_inner_func
return inner_func
a = outer_function()
inner functions don't return anything at all;
because of it, you don't need to use the return command.
you can just call them with this code:
inner_func_2()
but if your code is something else and bigger that returns something;
please edit and fix your question.
There is an formatting mistake in the question, the outer_function was not included.
def outer_function():
def inner_func(): # inner function
print("I am inner")
def inner_inner_func(): # inside the inner fucntion
print("I m inner inner")
def inner_inner_func_2(): #inside the child of inner child
print("I a inner inner 2")
return inner_inner_func_2
return inner_inner_func
return inner_func
outer_function()()()()
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))
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} )
I'm having some problems declaring a list. It seems like I cannot delete all the elements in the list. At the reset_a printout, it display an empty list but after another around of checking the list in myFunction, the previous element is still in the list. How can I declare a global list and use it all over others defined?
a = []
def reset_a():
global a
del a[:]
print a
def myFunction():
global a
#check other stuffs........... then..
print a
if data not in a:
a.append(data)
time.sleep(5)
reset_a()
if __name__=='__main__':
while True:
myFunction()
Edited: I found a way to get it done.
global a
a = []
def reset_a():
del a[:]
print a
def myFunction():
#check other stuffs...........and get 'data' then..
print a
if data not in a:
a.append(data)
time.sleep(5)
reset_a()
if __name__=='__main__':
while True:
myFunction()
rest_a() will be executed only if there is a new data not in a