Pyglet: variables in on_draw - python

My code uses on_draw() to display some figures, it uses global variables as the parameters of those figures.
I would like to know how to send local variables from the main() function to on_draw().
Is it possible?

I'm not familiar with Pyglet, but I'll try and answer.
If you want to use global variables from main(), declare the variables from within the on_draw() with the global keyword.
For example in the global space (outside of any functions).
x = 5
In your on_draw():
global x
#whenever you refer to x from now on, you will be referring to the x from main
#do something with x
x = 10
Now if you're in your main() again:
global x
print(x)
> 10

To add to Lee Thomas's answer, here is a complete snippet that can actually perform actions based on the value of the variable anywhere in the code:
import pyglet
x = 0 #declaring a global variable
window = pyglet.window.Window()#fullscreen=True
one_image = pyglet.image.load("one.png")
two_image = pyglet.image.load("two.png")
x = 10 #assigning the variable with a different value
one = pyglet.sprite.Sprite(one_image)
two = pyglet.sprite.Sprite(two_image)
print "x in main, ", x
#window.event
def on_draw():
global x #making the compiler understand that the x is a global one and not local
one.x = 0
one.y = 0
one.draw()
two.x = 365
two.y = 305
two.draw()
print "x in on_draw, ", x
pyglet.app.run()
Once I run the code, I get the output
Hope this helps

Related

How to change the global value of a parameter when using a function in python

This is what I want to achieve
Variable=0
Some_function(Variable)
print (Variable)
I want the output to be 1 (or anything else but 0)
I tried using global by defining some_function like this, but it gave me an error "name 'Variable' is parameter and global"
def Some_function(Variable):
x=Variable+1
global Variable
Variable=x
You are using Variable as your global variable and as function parameter.
Try:
def Some_function(Var):
x=Var+1
global Variable
Variable=x
Variable=0
Some_function(Variable)
print (Variable)
You should not use the same name for parameter and the globale variable
The error message seem clear enough. Also, you wouldn't need to pass Variable as a parameter if you are using a global.
If you define
def f():
global x
x += 1
Then the following script should not output an error :
x = 1 # global
f(x)
print(x) # outputs 2
Another possibility :
def f(y):
return y+1
Which you can use like this :
x = 1
x = f(x)
print(x) # 2
If you want to modify global variable, you should not use that name as function parameter.
var = 0
def some_func():
global var
var += 1
some_func()
print(var)
Just use global keyword and modify variable you like.
Variable = 0
def some_function(Variable):
global x
x = Variable + 1
some_function(Variable)
Variable = x
print(Variable)

Accessing variable in a function without calling it in Python

Here is my code
def function():
global x
x = 5
print (x)
How can I access the local variable x inside the function without calling the function itself?
It's not possible. A variable inside a function will only be after the function is called, else it is non-existent. Look into how locallocal,non-local, and global variables work.
def function():
global x
x = 5
print(x)
function()
else you should just put x outside the function().
Just put x = 5 outside the function

Why is global keyword not ignored even if it is unreachable? (Python)

I am really new to programming and Python, so please really forgive me for my ignorance.
I just learned that using global can make a variable inside function be a global one.
However, I discovered something not with my expectation:
I tried the following code in Python 3.8 (forgive me for my ignorance as I don't know what else information I should provide):
>>> x = 0
>>>
>>> def function():
... if False:
... global x
... x = 1
...
>>> function()
>>> print(x)
and the result is 1.
However, I expected the code to have the same effect as the following code:
>>> x = 0
>>>
>>> def function():
... x = 1
...
>>> function()
>>> print(x)
which the result should be 0.
In my mind, the statement inside if False should not be executed, so it sounds strange to me.
Also, personally, I think that in some situation I would expect the variable inside a function, whether local or global, to be dependent on other codes... what I mean is, I would like to change if False to something like if A == 'A', while (I hope) I can control whether the x is global/local according to my conditional statement.
I tried to change if to while, but it's the same... there isn't a infinite loop, but the code global x is still executed/compiled...
I admit that it may sounds naive, and perhaps it just won't work in Python, but I really wonder why... It seems that the code global x is unreachable, but how come it is not ignored?
Can anyone please tell me about the reason? I would like to know more about the mechanism behind compilation(?)
Any help would be appreciated, thank you!
In python the global statement (and the nonlocal statement) are very different from the normal python code. Essentially no matter where a global statement in a function is, it influences always the current codeblock, and is never "executed". You should think more of it as a compiler directive instead of a command.
Note that the statement itself must come before any usage of the variable it modifies, i.e.
print(x)
global x
is a syntax error. The global statement can only modify variable behavior in the whole codeblock, you can't first have a non-global variable that later gets global and you can also not have conditional global variable
(I couldn't really find good documentation for this behavior, here it says "The global statement is a declaration which holds for the entire current code block." and "global is a directive to the parser. It applies only to code parsed at the same time as the global statement." but that doesn't seem super clear to me.)
There are more compiler directives in python, although they don't always look like one. One is the from __future__ import statements which look like module imports but change python behavior.
Global is not in execution path but in a scope. The scope is whole function. Statements like if for don't make scopes. If you use any assignment you create local variable. The same with global or nonlocal you bind symbol to variable from outside.
As Stanislas Morbieu typed, see doc.
Programmer’s note: global is a directive to the parser. It applies only to code parsed at the same time as the global statement.
Not at execution time.
x = 1
def fun():
y = x + 1
print(f'local x = {x}, y = {y}')
fun()
print(f'global x = {x}')
# Output:
# local x = 1, y = 2
# global x = 1
In example above, y uses global x (and adds 1).
x = 1
def fun():
y = x
x = y + 1
print(f'local x = {x}')
fun()
print(f'global x = {x}')
# Output:
# UnboundLocalError: local variable 'x' referenced before assignment
Look at last example. It doesn't assign y from global x because assignment in second line creates local x and y can not read local x before x assignment. The same with:
x = 1
def fun():
if False:
x += 1
fun()
# Output
# UnboundLocalError: local variable 'x' referenced before assignment
x assignment creates local variable.
If you want to change global variable under condition you can use globals().
x = 1
def set_x(do_set, value):
if do_set:
globals()['x'] = value
print(f'global x = {x} (init)')
set_x(False, 2)
print(f'global x = {x} (false)')
set_x(True, 3)
print(f'global x = {x} (true)')
# Output
# global x = 1 (init)
# global x = 1 (false)
# global x = 3 (true)
Proxy
I you want to decide with variable you want to use later (in the same scope) you need some kind of proxy IMO.
x = 1
def fun(use_global):
x = 2 # local
scope = globals() if use_global else locals()
scope['x'] += 1
print(f'local ({use_global}): x = {scope["x"]}')
print(f'global: x = {x} (init)')
fun(False)
print(f'global: x = {x} (false)')
fun(True)
print(f'global: x = {x} (true)')
# Output:
# global: x = 1 (init)
# local (False): x = 3
# global: x = 1 (false)
# local (True): x = 2
# global: x = 2 (true)
Maybe you can think about refactoring of your code if you need it.
If you can change local variable name (if not use globals() as above), you can proxy:
use dict (like in example above)
use list (x=[1]) and usage x[0]
use object (with builtin dict), example:
class X:
def __init__(self, x):
self.x = x
x = X(1)
def fun(use_global):
global x
my_x = x if use_global else X(2)
my_x.x += 1
print(f'local ({use_global}): x = {my_x.x}')
print(f'global: x = {x.x} (init)')
fun(False)
print(f'global: x = {x.x} (false)')
fun(True)
print(f'global: x = {x.x} (true)')
# Output:
# global: x = 1 (init)
# local (False): x = 3
# global: x = 1 (false)
# local (True): x = 2
# global: x = 2 (true)
Note. Variables in Python are only references. It is way you can not change x = 1 without global (or globals()). You change reference to local value 1.
But you can change z[0] or z['x'] or z.x. Because z referents to list or dict or object and you modify it content.
See: https://realpython.com/python-variables/#object-references
You can check real object by id() function, ex. print(id(x), id(my_x)).
As per the Python documentation, global is a directive to the parser so it is taken into account before the execution, therefore it does not matter if the code is reachable or not. The variable is global for the entire scope, which is the function in your case.

Python : Can I global all variables in a function with a simple line?

I've create a fonction in my code that need a lots of variable and constants from the program. So, I've use the global with my varible and it's really long : 5 lines make all variables global...
I'm scearching a new way to make easely all variables global !
Please help me
this is a perfect annoying exemple :
( using pygame here but not important )
def GoWindow(w):
global screen, a, a_max, barPos, barSize, borderColor, bgBar, background, bg_loaded, current_load, a_dif, a_db, a_da, bar_percent, White, Black, Grey, Blue, Dark_Blue, Red, Dark_Red, Green, Dark_Green, Font,... #and it's continue....
if w == 'load' #rest of the fucntion
While I agree with the comments that there might be something wrong with the design of your program, you only need to declare global if you need to assign to those variables though.
x = 5
def print_x():
print(x)
def assign_x():
x = 10
def assign_global_x():
global x
x = 10
print_x() # prints 5
assign_x() # does nothing (only changes the local `x`)
print_x() # prints 5 (the global `x` is still 5)
assign_global_x() # assigns 10 to the global x
print_x() # prints 10 now
I.e. the output is
5
5
10

Global Variables in functions with if statements

Okay, I am currently doing a project to make a blackjack game in python and I'm having some trouble. One of my issues is I dont know when to define a variable as global, specifically in functions with if statements. If I have a global variable outside the if statement, do I have to claim that the variable is global within the if statement as well? For example:
x = 5
def add():
global x <--- ?
x += 1
if x == 7:
global x <--- ?
x = 5
I'm pretty sure I need the "global x" at the 1st question mark, but what about at the second question mark? Would I still need to put a "global x" within my if statement if I wanted my if statement to update a global variable? Or does the global x at the beginning of the function make the x's inside the if statement global? Also, if I wanted to return x here, where should I do it?
Only one global statement is enough.
From docs:
The global statement is a declaration which holds for the entire
current code block.
x = 5
def add():
global x
x += 1
if x == 7:
x = 5
Also, if I wanted to return x here, where should I do it?
If you're using global in your function then the return x must come after the global x statement, if you didn't use any global statement and also didn't define any local variable x then you can return x anywhere in the function.
If you've defined a local variable x then return x must come after the definition.

Categories