0

I am working in a personal project in Python, and I faced a problem that includes three of the files in this project. Let's say the files are named settings.py, functions.py and main.py.

In settings.py I have a class named settings, and inside this class I have a boolean variable named use_this_method and its value is False.

I have imported this class in the functions.py file, and I'm trying to change and print the value of the variable use_this_method from False to True. It works, but after this I want to print its value in the same way in the main.py file, but it prints False instead of True.

settings.py

class settings:
    use_this_method = False

functions.py

from settings import settings
setting = settings()

def change_method():
    setting.use_this_method = True
    print(setting.use_this_method)

main.py

from functions import *
from settings import settings
setting = settings()

change_method()
print(setting.use_this_method)

In the output I am expecting:

True
True

but I get

True
False
1
  • You are changing the value on an instance, not the class. Commented Aug 28, 2019 at 0:44

1 Answer 1

3

The setting instance in your functions.py is separate from the one in your main.py. If you print(id(setting)) in both modules you will see that.

You should use class attributes for your use case.Your functions.py then becomes:

from settings import settings

def change_method():
    settings.use_this_method = True
    print(setting.use_this_method)

and your main.py:

from functions import *
from settings import settings

change_method()
print(settings.use_this_method)

As a side note, it is a good idea to stick to Python naming conventions detailed in PEP-8 if you have just started learning Python.

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

Comments

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.