2

I have a simple python package named my_package with three files:

init.py

from .a import func
from .settings import var

settings.py

var = 1

a.py

import .settings

def func():
    settings.var = 2

When I add this package to PATH and import it I run below script, couldn't get expected result:

import my_package

my_package.func()
print(my_package.var)

I am expecting to get '2' but it returns '1'. What am I doing wrong here?

Elgin Cahangirov
  • 1,327
  • 2
  • 14
  • 31

1 Answers1

-1

It happens because during import my_package a my_package.var is set to refer to int with value of 1. After running my_package.func() this reference is not touched, however my_package.settings.var is changed to point at new int object with value 2.

import my_package  # imports my_package.var with value 1 

my_package.func()  # sets my_package.settings.var to 2
print(my_package.var)  # prints 1
print(my_package.settings.var)  # prints 2

If you try to do the same with list, you can make it will work differently. By not creating new object at my_package.settings.list_var but rather modifying an entry in existing list.

# __init__.py
from .a import func
from .settings import list_var

_

# settings.py
list_var = [1]

_

# a.py
import .settings

def func():
    settings.list_var[0] = 2

Now running the similar code will actually change the list_var

import my_package  # imports my_package.var with value 1 

print(my_package.var[0])  # prints 1
my_package.func()  # sets list_var to [2]
print(my_package.var[0])  # prints 2
matusko
  • 2,561
  • 14
  • 26