0

I have a code module.py that is imported into my main.py so I can use its functions, which are defined with def. The imported module only has def functions.

There are some if statements in the functions that I'd wish to manipulate automatically from main.py.

Like for example

main.py

import module as md


BoolIfState=True

for i in range(10):
    md.runfunction(i)

module.py

def runfuntion(i):
   if BoolIfState:
        print i
   else:
        print i-10

return None

Here the definition of BoolIfState in main.py changes how runfunction from module behaves. I tried adding global BoolIfState inside the function but it didn't change the behavior.

Obviously, the actual codes are much more difficult but it's the same basic idea.

Is there a way to do this?


Edit: I am avoiding giving the variable as an input to the function because then it will become cluttered given all the variables that would need to be added. I need to the same thing to approximately 5 variables, and with it, the cleanliness of having functions defined inside the module are lost.

2
  • 1
    I would call it an antipattern (explicit is better than implicit). It is probably better to make it a function parameter(s) Commented Oct 7, 2019 at 20:57
  • Yes that has been how I have been doing it but would prefer finding a way around it Commented Oct 7, 2019 at 22:11

1 Answer 1

2

You could package all of the global variables into a singleton class (singleton class example).

This way you could maintain one class instance with member variables that could be used/accessed across your codebase.

Sign up to request clarification or add additional context in comments.

2 Comments

I wish I could say I understand how I could implement that but I don't. I have been reading about singleton but it still doesn't make sense to me. I will keep reading though, hopefully I will understand how I could use that.
Basically, it is just like a normal class, but there is a special clause in the constructor that limits the number of instances to 1. ` def __init__(self, arg): if not OnlyOne.instance: OnlyOne.instance = OnlyOne.__OnlyOne(arg) else: OnlyOne.instance.val = arg ` This way, you can use the class in your code, and as long as it has already been initialized somewhere, you can then access the class variables. In the example in the link, just replace self.val with your parameter(s).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.