Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite global variables

Tags:

python

I have two modules:

constants.py

def define_sizes(supersample):    
    global SUPERSAMPLE
    global WIDTH
    global HEIGHT
    global LINE_WIDTH

    SUPERSAMPLE = supersample
    WIDTH = 1280*SUPERSAMPLE
    HEIGHT = 854*SUPERSAMPLE
    LINE_WIDTH = 1*SUPERSAMPLE

define_sizes(1)

test.py

from constants import *


print(WIDTH, HEIGHT, LINE_WIDTH)
# Draw something

define_sizes(4)

print(WIDTH, HEIGHT, LINE_WIDTH)
# Draw the same thing, but bigger

The result is:

1280 854 1
1280 854 1

I would expect to get:

1280 854 1
5120 3416 4

Why is that? What am I missing? Can I fix it to give expected results?

like image 623
Fenikso Avatar asked Oct 27 '25 08:10

Fenikso


2 Answers

You can't share global variables across modules in Python as such. You could use a config module, by importing it where ever you need it in the project and since there would only be one instance of it, you can use that as a global. It is described in the documentation.

like image 140
adarsh Avatar answered Oct 28 '25 20:10

adarsh


I recommend something like the answer by adarsh for "real code", but if what you need to do is just to hack some existing code as quickly as possibly, you might try reimporting the constants, with a test.py like:

from constants import *

print(WIDTH, HEIGHT, LINE_WIDTH)

define_sizes(4)

from constants import *

print(WIDTH, HEIGHT, LINE_WIDTH)

You would also have to modify constants.py so that it doesn't reset the SUPERSAMPLE to 1 when reimporting, something like:

def define_sizes(supersample):
    global SUPERSAMPLE
    global WIDTH
    global HEIGHT
    global LINE_WIDTH

    SUPERSAMPLE = supersample
    WIDTH = 1280*SUPERSAMPLE
    HEIGHT = 854*SUPERSAMPLE
    LINE_WIDTH = 1*SUPERSAMPLE

if not 'SUPERSAMPLE' in globals():
    define_sizes(1)
like image 36
skagedal Avatar answered Oct 28 '25 21:10

skagedal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!