Is global variable static in python - 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.

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?

Exec can't access variables in it's parent environment

My friend asked me to build a function that can execute code in a for loop so, I was doing that and I was using exec in the same file I was declaring a variable name, now when I access name from exec, it says NameError: name 'name' is not defined
This thing is in multiple files, one that runs everything, second that includes all functions and one that calls all functions
I have tried to define variables inside exec and sure, it works.
I have tried Accessing variables in functions.py(File that contains every function) file and it works too.
I have tried merging functions.py and test.py(the file that's using exec) and then running it directly through python and it worked
My functions.py file
def forloop(current, maximum, code):
for x in range(current, maximum):
exec(str(code), globals())
My 'test.py'(It's the one where I call functions)
from functions import *
name = 'Ameer'
forloop(1,3,"""
echo(name)
""")
And, I am running it all through another exec in my 'runner.py'
from functions import *
file = open('test.py', "r+")
content = file.read()
exec(content)
Now, it's giving me an error saying NameError: name 'name' is not defined when it is defined. Please can you guys help me with this issue
You need to use the variables from the place where forloop is called.
import inspect
def forloop(current, maximum, code):
frame = inspect.currentframe().f_back
for x in range(current, maximum):
exec(str(code), frame.f_globals, frame.f_locals)

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.

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()

Making all variables in a scope global or importing a module inside another module

I have a package with two modules in it. One is the __init__ file, and the other is a separate part of the package. If I try from mypackage import separatepart, the code in the __init__ module is run, which will run unneeded code, slowing down the importing by a lot. The code in separate part won't cause any errors, and so users should be able to directly import it without importing the __init__ module.
Since I can't figure out a way to do this, I thought I should include a function in the __init__ file that does everything so nothing would be done directly, but in order to do this, I would need to have any variables set to be global. Is there any way to tell Python that all variables are global in a function, or to not run the __init__ module?
dthat I know of, there is not way to specify that all variables are global but you can import the module while you are in the module. just make sure that you do it in a function that isn't called at the top level, you are playing with infinite recursion here but a simple use should be safe.
#module.py
foo = bar = 0 # global
def init()
import module as m
m.foo = 1
m.bar = 2 # access to globals
if init was called at the top level, then you have infinite recursion but it sounds like the whole point of this is to avoid this code running at the top level, so you should be safe. Since you want to do this in the __init__.py file, just import the top level of the package.
It occurred to me on a walk that there's no problem with recursion here because the top level code will only run once on initial import.

Categories

Resources