Import creates unexpected references to objects depending on whether a module is a file, or when it is part of a package

I have subtle import issue that creates variables with references to objects different to what I expect, and it all depends on whether the module I’m writing is imported “as is” or as part of a package.

Let’s say I have a simple module that defines a Config class and a function to set it up:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class Config:
def __init__(self, **kwargs):
if kwargs.get("print_keys", None):
self.print_keys = kwargs.pop("print_keys")
else:
self.print_keys = ["centre", "shortName"]
rcParams = Config()
def set_config(config=None):
global rcParams
print("Before change:", id(rcParams))
if config is None:
config = Config()
rcParams = config
print("After change:", id(rcParams))
</code>
<code>class Config: def __init__(self, **kwargs): if kwargs.get("print_keys", None): self.print_keys = kwargs.pop("print_keys") else: self.print_keys = ["centre", "shortName"] rcParams = Config() def set_config(config=None): global rcParams print("Before change:", id(rcParams)) if config is None: config = Config() rcParams = config print("After change:", id(rcParams)) </code>
class Config:
    def __init__(self, **kwargs):
        if kwargs.get("print_keys", None):
            self.print_keys = kwargs.pop("print_keys")
        else:
            self.print_keys = ["centre", "shortName"]


rcParams = Config()


def set_config(config=None):
    global rcParams
    print("Before change:", id(rcParams))
    if config is None:
        config = Config()
    rcParams = config
    print("After change:", id(rcParams))

If I save this in a module named simple.py, then I can successfully test it with this module:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># import gribtool as gt # note this line is uncommented later
import simple as gt # note this line is commented later
def test_set_config():
config = gt.Config(print_keys=["centre"])
print("Initial rcParams id:", id(gt.rcParams))
gt.set_config(config=config)
print("Updated rcParams id:", id(gt.rcParams))
assert gt.rcParams.print_keys == ["centre"]
test_set_config()
</code>
<code># import gribtool as gt # note this line is uncommented later import simple as gt # note this line is commented later def test_set_config(): config = gt.Config(print_keys=["centre"]) print("Initial rcParams id:", id(gt.rcParams)) gt.set_config(config=config) print("Updated rcParams id:", id(gt.rcParams)) assert gt.rcParams.print_keys == ["centre"] test_set_config() </code>
# import gribtool as gt # note this line is uncommented later
import simple as gt     # note this line is commented later


def test_set_config():
    config = gt.Config(print_keys=["centre"])
    print("Initial rcParams id:", id(gt.rcParams))
    gt.set_config(config=config)
    print("Updated rcParams id:", id(gt.rcParams))
    assert gt.rcParams.print_keys == ["centre"]


test_set_config()

The output is:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Initial rcParams id: 128205347716160
Before change: 128205347716160
After change: 128205347716832
Updated rcParams id: 128205347716832
</code>
<code>Initial rcParams id: 128205347716160 Before change: 128205347716160 After change: 128205347716832 Updated rcParams id: 128205347716832 </code>
Initial rcParams id: 128205347716160
Before change: 128205347716160
After change: 128205347716832
Updated rcParams id: 128205347716832

So far so good. Now, the problem is that I want this to be part of a package. I move this module to a package (a directory) named gribtool, and then I create the __init__.py file with the expected content:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from .simple import *
</code>
<code>from .simple import * </code>
from .simple import *

Then, I uncomment the line with import gribtool as gt in the test module above, and then it fails with this output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Initial rcParams id: 134251413862864
Before change: 134251413862864
After change: 134251413864064
Updated rcParams id: 134251413862864
Traceback (most recent call last):
File "/home/navarro/AEMET/GRIB_TOOL/test_config.py", line 13, in <module>
test_set_config()
File "/home/navarro/AEMET/GRIB_TOOL/test_config.py", line 10, in test_set_config
assert gt.rcParams.print_keys == ["centre"]
AssertionError
</code>
<code>Initial rcParams id: 134251413862864 Before change: 134251413862864 After change: 134251413864064 Updated rcParams id: 134251413862864 Traceback (most recent call last): File "/home/navarro/AEMET/GRIB_TOOL/test_config.py", line 13, in <module> test_set_config() File "/home/navarro/AEMET/GRIB_TOOL/test_config.py", line 10, in test_set_config assert gt.rcParams.print_keys == ["centre"] AssertionError </code>
Initial rcParams id: 134251413862864
Before change: 134251413862864
After change: 134251413864064
Updated rcParams id: 134251413862864
Traceback (most recent call last):
  File "/home/navarro/AEMET/GRIB_TOOL/test_config.py", line 13, in <module>
    test_set_config()
  File "/home/navarro/AEMET/GRIB_TOOL/test_config.py", line 10, in test_set_config
    assert gt.rcParams.print_keys == ["centre"]
AssertionError

As you can see, the problem is that the rcParams that is being modified within the set_config function is different from the one in the simple module despite the global instruction.

How can I make sure I’m referring to the right objects?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật