How to use global functions in function from separate module? - python

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?

Related

Is global variable static in python

This is my utils.py
detector = cv2.mcc.CCheckerDetector_create()
def process():
print(detector)
main.py
for i in range(100):
process()
This question might sound stupid.
As the variable detector in process() is initiated everytime I call process() if I put it inside the function process() so I change it as a global variable. Will it be created only once?
The variable will be created when the code that creates it is executed. In the case of detector, that code is at the module level. It will be executed when the module is imported, and never again. There's no code anywhere in your example to create any objects to replace it.

global variable for recursive functions in 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.

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.

Declaration functions in python after call

$ cat declare_funcs.py
#!/usr/bin/python3
def declared_after():
print("good declared after")
declared_after()
$ python3 declare_funcs.py
good declared after
Change call place:
$ cat declare_funcs.py
#!/usr/bin/python3
declared_after()
def declared_after():
print("good declared after")
$ python3 declare_funcs.py
Traceback (most recent call last):
File "declare_funcs.py", line 4, in <module>
declared_after()
NameError: name 'declared_after' is not defined
Is there way to declare only header of function like it was in C/C++?
For example:
#!/usr/bin/python3
def declared_after() # declaration about defined function
declared_after()
def declared_after():
print("good declared after")
I found this Declare function at end of file in Python
Any way there appear another function in the beginning like wrapper, and this wrapper must be called after declaration of wrapped function, this is not an exit. Is there more elegant true-python way?
You can't forward-declare functions in Python. It doesn't make a lot of sense to do so, because Python is dynamically typed. You could do something silly like this, and what would expect it to do?
foo = 3
foo()
def foo():
print "bar"
Obviously, you are trying to __call__ the int object for 3. It's absolutely silly.
You ask if you can forward-declare like in C/C++. Well, you typically don't run C through an interpreter. However, although Python is compiled to bytecode, the python3 program is an interpreter.
Forward declaration in a compiled language makes sense because you are simply establishing a symbol and its type, and the compiler can run through the code several times to make sense of it. When you use an interpreter, however, you typically can't have that luxury, because you would have to run through the rest of the code to find the meaning of that forward declaration, and run through it again after having done that.
You can, of course, do something like this:
foo = lambda: None
foo()
def foo():
print "bar"
But you instantiated foo nonetheless. Everything has to point to an actual, existing object in Python.
This doesn't apply to def or class statements, though. These create a function or class object, but they don't execute the code inside yet. So, you have time to instantiate things inside them before their code runs.
def foo():
print bar()
# calling foo() won't work yet because you haven't defined bar()
def bar():
return "bar"
# now it will work
The difference was that you simply created function objects with the variable names foo and bar representing them respectively. You can now refer to these objects by those variable names.
With regard to the way that Python is typically interpreted (in CPython) you should make sure that you execute no code in your modules unless they are being run as the main program or unless you want them to do something when being imported (a rare, but valid case). You should do the following:
Put code meant to be executed into function and class definitions.
Unless the code only makes sense to be executed in the main program, put it in another module.
Use if __name__ == "__main__": to create a block of code which will only execute if the program is the main program.
In fact, you should do the third in all of your modules. You can simply write this at the bottom of every file which you don't want to be run as a main program:
if __name__ = "__main__":
pass
This prevents anything from happening if the module is imported.
Python doesn't work that way. The def is executed in sequence, top-to-bottom, with the remainder of the file's contents. You cannot call something before it is defined as a callable (e.g. a function), and even if you had a stand-in callable, it would not contain the code you are looking for.
This, of course, doesn't mean the code isn't compiled before execution begins—in fact, it is. But it is when the def is executed that declared_after is actually assigned the code within the def block, and not before.
Any tricks you pull to sort-of achieve your desired effect must have the effect of delaying the call to declared_after() until after it is defined, for example, by enclosing it in another def block that is itself called later.
One thing you can do is enclose everything in a main function:
def main():
declared_after()
def declared_after():
print("good declared after")
main()
However, the point still stands that the function must be defined prior to calling. This only works because main is called AFTER declared_after is defined.
As zigg wrote, Python files are executed in order they are written from top to bottom, so even if you could “declare” the variable before, the actual function body would only get there after the function was called.
The usual way to solve this is to just have a main function where all your standard execution stuff happens:
def main ():
# do stuff
declared_after();
def declared_after():
pass
main()
You can then also combine this with the __name__ == '__main__' idiom to make the function only execute when you are executing the module directly:
def main ():
# do stuff
declared_after();
def declared_after():
pass
if __name__ == '__main__':
main()

Behavior of Python exec() differs depending on the where it is called from

I have a Python script 'runme.py' that I am trying to execute from 'callerX.py' below. I am using exec(open(filename).read()) to accomplish this task. The script being executed contains a simple class that attempts to call the 'time()' function both from the global namespace & inside a function.
In all of the examples below, we are executing the following file using exec():
# runme.py
# this code is being exec()'d by the stand-alone examples 1-3 below:
from time import *
class MyClass():
def main(self):
print("Local tracepoint 1")
t = time()
print("Local tracepoint 2")
mc = MyClass()
print("Tracepoint 1")
gt = time()
print("Tracepoint 2")
mc.main()
print("Tracepoint 3")
caller1.py: (this works properly, the 'time' function can be used within MyClass.main())
print("Run from main scope:")
exec(open("runme.py").read())
caller2.py: (this does not work, fails with the Exception "NameError: global name 'time' is not defined" inside MyClass.main())
def Run():
exec(open("runme.py").read())
print("Run from function:")
Run()
caller3.py: (this works properly, both exec()s run without Exceptions)
def Run():
exec(open("runme.py").read())
print("Run from main scope:")
exec(open("runme.py").read())
print("Run from function:")
Run()
Note that in the examples above, the calls to the time() function in the global namespace of 'runme.py' always work, and the calls to the time() function from MyClass.main() only sometimes work, depending on whether or not the file runme.py was exec()'d from within a function.
If we call exec() from outside a function (caller1.py), it works. If we call exec() from inside a function (caller2.py), it fails with an Exception. If we call exec() from outside a function and subsequently from inside a function (caller3.py), both calls to exec() run without an Exception.
This behavior seems inconsistent. Any ideas? I know this is a contrived example, however, it was distilled from a much more complicated program that has requirements that have brought us to this juncture.
This has probably to do with how 'from x import *' works. If you call this from 'top-level', it gets imported into globals() for the whole module.
However, if you call this inside a function, it gets imported only into locals() - in the function. The exec() gets evaluated inside a function in caller2; therefore the import * doesn't get into globals() and the 'inner' main function doesn't see it.
BTW: it is intersting that if you try code like this:
def run():
from time import *
def test():
print time()
test()
run()
You will get an exception: SyntaxError: import * is not allowed in function 'run' because it is contains a nested function with free variables
But that is precisely what you are doing with the exec, but it somehow surprisingly sneaks through.
However - considering the other answer here - why don't you use something other instead? Look at the 'imp' module documentation - in particular functions find_module and load_module.
Here's an idea: don't use exec. Basically every time I've seen someone use exec or eval it's because they don't know that a better way to accomplish the same thing already exists; it's a crutch that hinders writing dynamic code, not a way to write code that's somehow more dynamic.

Categories

Resources