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
Selcuk
  • 57,004
  • 12
  • 102
  • 110
CurlyError
  • 305
  • 2
  • 15

1 Answers1

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.

Selcuk
  • 57,004
  • 12
  • 102
  • 110