MAx Shvedov
MAx Shvedov

Reputation: 355

Python 3, Global Variables, Modules

how can I move this code to a function in a module? I have global var 'last_msg' and 'fake'. I was trying use 'global' for 'last_msg' in my function, but it out of scope because function in a module, but 'last_msg' in main scope.

main.py

from module import Timeout

last_msg = {'Foo': 0}
name = 'Foo'
fake = False
timeout = 3

fake = Timeout(fake, name, timeout)

>> NameError: name 'last_msg' is not defined

<>

module.py

def Timeout(fake, name, timeout):
    global last_msg

    if not fake:
        if name not in last_msg:
            last_msg[name] = 0

        if last_msg[name] > 0:
            last_msg[name] -= 1
            fake = True
        else:
            last_msg[name] = timeout
    else:
        if name in last_msg:
            last_msg[name] = 0

    return fake

Upvotes: 1

Views: 616

Answers (2)

darthsidious
darthsidious

Reputation: 3081

This link has some information about how you can access globals and how python treats globals. For that the code will be:

module.py
def Timeout(fake, name, timeout):
    import main

    if not fake:
        if name not in main.last_msg:
            main.last_msg[name] = 0

        if main.last_msg[name] > 0:
            main.last_msg[name] -= 1
            fake = True
        else:
            main.last_msg[name] = timeout
    else:
        if name in main.last_msg:
            main.last_msg[name] = 0

    return fake

and the main.py would look like this:

last_msg = {'Foo': 0}
from module import Timeout

# last_msg = {'Foo': 0}
name = 'Foo'
fake = False
timeout = 3

fake = Timeout(fake, name, timeout)

Upvotes: 3

MAx Shvedov
MAx Shvedov

Reputation: 355

Seems I've done it.

main.py

from module import Timeout

last_msg = {'Foo': 0}
name = 'Foo'
fake = False
timeout = 3

fake, last_msg = Timeout(fake, name, last_msg, timeout)

<>

module.py

def Timeout(fake, name, last_msg, timeout):
    if not fake:
        if name not in last_msg:
            last_msg[name] = 0

        if last_msg[name] > 0:
            last_msg[name] -= 1
            fake = True
        else:
            last_msg[name] = timeout
    else:
        if name in last_msg:
            last_msg[name] = 0

    return fake, last_msg

Upvotes: 0

Related Questions