Understand Python Path — Import Variable From __init__.py (update)

This is an update for How to (Python) get value from __init__ in same dir | by 洪健翔 Hung, Chien-hsiang | Aug, 2022 | Medium. Make sure you have read the previous one. Let’s get started!

https://miro.medium.com/max/1400/0*u0-PawlvltYTMdx-

Photo by AltumCode on Unsplash

Dir Structure:

—ModuleName

| — __init__.py

| — bar.py

__init__.py:

1
colour_map_earth_tone = ['#E8D0A9', '#B7AFA3', '#C1DAD6', '#b7baba', '#ACD1E9', '#6D929B']

bar.py:

1
2
3
4
if __name__ == '__main__': 
  from __init__ import colour_map_earth_tone
else: 
  from . import colour_map_earth_tone

This way you can successfully import the var from __init__.py when both testing and production using.

original q: Can I use __init__.py to define global variables?

Contact Me: Hung, Chien-Hsiang (chienhsiang-hung.github.io)