global variable for recursive functions in python - python

I am using pyhton to for a recursive function named sphereinput the function needs to return a variable name result as output.By declaring it as global in recursive function I wil not have to use return at the end of function.
Will the function return result having the correct answer when called in main file of my program.
My reservation is that for each call to the function sphereinput in itself the global variable result will be updated accordingly ,right?
def sphereinput(parameters)
global result
Recursive call to sphereinput
result=assigned value
Note that I did not use return statement here.Do I have to?
Also when i define it in same file as main code after every call to function it starts executing the code lines below function again which are part of main code and must not be executed.
If i have to define this function in another file how do i call it from main file and then which variables will have to be defined global both in main and function code file?

The result will be updated accordingly, but not returned unless you explicitly do so.
I do not know what you mean with
Also when i define it in same file as main code after every call to
function it starts executing the code lines below function again which
are part of main code and must not be executed.
To call it from main file you have to first import the module (=file) and then call its function:
import myfile
myfile.sphereinput(args)
You do not have to define the result variable anywhere else as long as you make sure that you don't use it before you call sphereinput.
You can call your function recursively in another way as well, which does not require a global variable:
while True:
temp = sphereinput(args)
if temp is None:
break
result = temp
Here you simply return None when you do not want any further recursions.

Related

How to use global functions in function from separate module?

I have a program that writes a separate in order to make a series of similar functions. These functions are to call another function, checkbuy, from the main source code. Whenever I try this, it says it's not defined. Globalizing the main function in the module functions fails.
Module function:
def buyMagikarp():
global pokenums
if checkbuy(10,1): #calling the function from main file
pokenums['Magikarp']+=1
Magikarp.config(text='Magikarp: '+str(pokenums['Magikarp']))
This function is used inside of a Tkinter Button object, and is successfully called when the button is clicked.
Function in main:
def checkbuy(price,amount):
global coin, coingainnum
if coin >= price:
coin-=price
updatecoin()
coingainnum+=amount
return True
else:
return False
Module function works in works when in main.
How to call function from function in local namespace?

Python how to include function from another file

I have a problem with including a function from another file to main executable script. I have too many functions and my main script became too long and hard to manage. So i've decided to move every function to separate file and than attach/include it. I've read nearly any relative post here to resolve my problem but no luck. Let's see:
main_script.py
==================
from folder.another_file import f_fromanotherfile
class my_data:
MDList=[]
work=my_data()
def afunction():
f_fromanotherfile()
return
and
another_file.py
=====================
#In this file i've put just function code
def f_fromanotherfile():
a=[1,2,3,4]
work.MDList=a
return
And this is the error:
line 11, in f_fromanotherfile
work.MDList=a
NameError: global name 'work' is not defined
Help me please
The scope of 'work' is its module, main_script.py, so you cannot access it from another module. Make 'work' an argument of f_fromanotherfile instead:
In another_file.py:
def f_fromanotherfile(work):
# function body stays the same
In main_module.py:
def afunction():
f_fromanotherfile(work)
because in another_file.py
#In this file i've put just function code
def f_fromanotherfile():
a=[1,2,3,4]
work.MDList=a
return
work is not a global variable.And then doing assignment to it can't work.
u should change ur code to: another_file.py
#In this file i've put just function code
def f_fromanotherfile():
global work
a=[1,2,3,4]
work.MDList=a
return
with the global keyword u can say the variable in so-called global scope and do ur assignment.
PS:kind of like the keyword extern in C?

How to pass variables over functions in python 3

#Test
def test():
test1 = input("Type something: ")
test()
print(test1)
print(test1)
NameError: name 'test1' is not defined
'test1' is not defined
This is bothering me. I'm learning python and trying to write a small game for practice, and it seems that variables that are declared in a function don't carry over. Is there a way to get by this? Am I not supposed to use test() to close the function? Or should I figure out and use a class instead? Or perhaps is it just a quirk of python? Thanks for any help.
By default, all the names assigned inside a function definition are put in the local scope (the
namespace associated with the function call). If you need to assign a name that
lives at the top level of the module enclosing the function, you can do so by declaring
it in a global statement inside the function. If you need to assign a name
that lives in an enclosing def, as of Python 3.X you can do so by declaring it in a
nonlocal statement.
Read this: https://docs.python.org/3.4/tutorial/classes.html#python-scopes-and-namespaces
You need to return the value and store the returned value to print it.
def test():
test1 = input("Type something: ")
return test1
a = test()
print(a)
In general, functions should rely on arguments and return values instead of globals.
def test():
test1 = input("Type something: ")
These two lines define a function called test. When test is called (test()), the line inside will be run. The line inside assigns input to the variable test1. But test1 is scoped to the test function -- the name test1 only exists inside the function, so once the function ends, the name disappears.
Functions are called to produce output (or side-effects, but in this case, output). You do that by using the return keyword to end your function and return a variable. In this case, you could do return test1 inside your function (technically you could just to return input(...) directly too, and skip the creation of the variable entirely).
test()
This calls the function. You can do this at any time after the function is defined; you don't need to do it to "close" the function.
If you modify your function to return a value, then you'll need to do something with the return value on this line. Something like result = test(). That assigns the return value of test to the result variable.
print(test1)
This isn't working because test1 only exists inside the function namespace, and you are calling this line outside of the function namespace. If you've made the changes I suggested above, you can do print(result) instead.

Python function invoked before definition

I am confused about the below given code in Python where a function has been called before its definition. Is it possible? Is it because the function does not return a value?
from Circle import Circle
def main():
myCircle = Circle()
n = 5
printAreas(myCircle, n) #The function is called here
def printAreas(c, times):
xxxx
xxxx
main()
What happens in your program:
main is defined, with a reference to printAreas in its body—note, this is just a reference, not a call
printAreas is defined
main is invoked
main calls printAreas.
So all is good—you are allowed to reference any names you want at any time you want, as long as you ensure these names will have been defined (bound to a value) by the time the code containing the reference is executed:
def foo():
print bar # reference to as-of-yet non-existent bar
# calling foo here would be an error
bar = 3
foo() # prints 3
Python will first parse your file, register all function, variables, etc into the global namespace. It will then call the main function, which will then call printAreas. At the time, both functions are in your script namespace, and hence perfectly accessible.
The thing that is confusing you is just the reading order.
You are calling main at the end of your program. This allows the interpreter to load up all your functions and then start your main function.

python - get list of all functions in current module. inspecting current module does not work?

I have following code
fset = [ obj for name,obj in inspect.getmembers(sys.modules[__name__]) if inspect.isfunction(obj) ]
def func(num):
pass
if __name__ == "__main__":
print(fset)
prints
[]
however this
def func(num):
pass
fset = [ obj for name,obj in inspect.getmembers(sys.modules[__name__]) if inspect.isfunction(obj) ]
if __name__ == "__main__":
print(fset)
prints
[<function func at 0x7f35c29383b0>]
so how can fset be list of all functions in current module where fset is defined at the top of all functions ?
EDIT 1: What I am trying to do is
def testall(arg):
return any(f(arg) for f in testfunctions)
def test1(arg):
#code here
# may call testall but wont call anyother test*
def test2(arg):
#code here
# may call testall but wont call anyother test*
More test function may be added in the future. So thats the reason of fset/testfunctions
EDIT 1: What I am trying to do is
def testall(arg):
return any(f(arg) for f in testfunctions)
def test1(arg):
#code here
# may call testall but wont call anyother test*
This works just fine:
def testall(arg):
testfunctions = [obj for name,obj in inspect.getmembers(sys.modules[__name__])
if (inspect.isfunction(obj) and
name.startwith('test') and name != 'testall')]
return any(f(arg) for f in testfunctions)
def test1(arg):
#code here
# may call testall but wont call anyother test*
In this case, testfunctions isn't evaluated until testall is called, so there's no problem here—by that time, all top-level module code (including the test1 definition) will have been evaluated, so testfunctions will get all of the top-level functions. (I'm assuming here that testall or test1 is being called from an if __name__ == '__main__' block at the bottom of the module, or another script is doing import tests; tests.test1(10), or something similar.)
In fact, even if you explicitly named test1 and test2, there would be no problem:
def testall(arg):
testfunctions = ('test1',)
return any(f(arg) for f in testfunctions)
def test1(arg):
#code here
# may call testall but wont call anyother test*
Again, test1 is already defined by the time you call testall, so everything is fine.
If you want to understand why this works, you have to understand the stages here.
When you import a module, or run a top-level script, the first stage is compilation (unless there's already a cached .pyc file). The compiler doesn't need to know what value a name has, just whether it's local or global (or a closure cell), and it can already tell that sys and inspect and test1 are globals (because you don't assign to them in testall or in an enclosing scope).
Next, the interpreter executes the compiled bytecode for the top-level module, in order. This includes executing the function definitions. So, testall becomes a function, then test1 becomes a function, then test2 becomes a function. (A function is really just the appropriate compiled code, with some extra stuff attached, like the global namespace it was defined in.)
Later, when you call the testall function, the interpreter executes the function. This is when the list comprehension (in the first version) or the global name lookup (in the second) happens. Since the function definitions for test1 and test2 have already been evaluated and bound to global names in the module, everything works.
What if you instead later call test1, which calls testall? No problem. The interpreter executes test1, which has a call to testall, which is obviously already defined, so the interpreter calls that, and the rest is the same as in the previous paragraph.
So, what if you put a call to testall or test1 in between the test1 and test2 definitions? In that case, test2 wouldn't have been defined yet, so it would not appear in the list (first version), or would raise a NameError (second version). But as long as you don't do that, there's no problem. And there's no good reason to do so.
If you're worried about the horrible performance cost of computing testfunctions every time you call testall… Well, first, that's a silly worry; how many times are you going to call it? Are your functions really so fast that the time to call and filter getmembers even shows up on the radar? But if it really is a worry, just cache the value in your favorite of the usual ways—mutable default, privat global, function attribute, …:
def testall(arg, _functions_cache=[]):
if not _functions_cache:
_functions_cache.extend([…])
It can't be. Function definitions are executed in Python. The functions don't exist until their definition is executed. Your fset variable can't be defined until after the functions are defined.
To exclude any imported functions this works:
import sys
import inspect
[obj for name,obj in inspect.getmembers(sys.modules[__name__])
if (inspect.isfunction(obj) and
name.startswith('test') and
obj.__module__ == __name__)]

Categories

Resources