Ako Cruz
Ako Cruz

Reputation: 353

Changing variable on another module for functions

I have made two py files, in which main.py contains:

import module

module.Print("This should not appear.")

module.Silence = False
module.Print("This should appear.")

The module imported is module.py which contains:

Silence = True


def Print(Input, Sil= Silence):
    if Sil == False:
        print(Input)

The expected result should be:

This should appear

The result:

Upvotes: 0

Views: 179

Answers (2)

VPfB
VPfB

Reputation: 17247

I think you are looking for a function with a default setting that can be dynamically changed. This will use the global Silence only if the sil argument is omitted in Print() function call.

def Print(input, sil=None):
    if sil is None:
        sil = Silence
    if not sil:
        print(input)

Upvotes: 0

Gerrat
Gerrat

Reputation: 29680

The issue is that you've defined your Print function with a default argument of True (since Silent == True when this module is imported, and the function created). Changing the module variable, Silent to False later isn't going to affect this function definition in any way. It's already set in stone.

You could achieve what it looks like you want to doing something like (in module.py):

Silence = [True]

def Print(Input, Sil= Silence):
    if Sil[0] == False:
        print(Input)

...

And then setting module.Silence[0] = False in main.py.

[I'm assuming the goal here was to call the function without passing in an explicit Sil argument. You can certainly just pass in an explicit second argument and have the function perform exactly how you expect instead]

Upvotes: 1

Related Questions