1

Currently I have a python file that goes like this (really simplified):

u = 30
colors = ('blue', 'red')
grid = [0, 1]

class entity:
    def __init___(self, x, color)
        self.x = x
        self.color = color

    def move(self):
        print(grid[self.x + 1], self.color)
        

foo = entity(0, 'blue')
bar = entity(0, 'red')
while true:
    foo.move()
    bar.move()

I tried to split it out and I got this:

# initialisation.py
u = 30
colors = ('blue', 'red')
# grid_map.py
from initialisation import u, colors
grid = [0, 1]
# classes.py
from map import u, colors, grid  # or *
class entity:
    def __init___(self, x, color)
        self.x = x
        self.color = color

    def move(self):
        print(grid[self.x + 1], self.color)

# objects.py
from classes import u, colors, grid, entity  # or *
foo = entity(0, 'blue')
bar = entity(0, 'red')
# main.py
from objects import u, colors, grid, entity, foo, bar  # or *
while true:
    foo.move()
    bar.move()

Now, I feel like I should be importing in a way that isn't this import-chain from one file to the next, but I'm unsure exactly how.

(hopefully this is a minimal, reproducible example)

Adrien Levert
  • 964
  • 6
  • 15

1 Answers1

4

Importing as a chain isn't useful, except for very specific instances where a module adds or defines functionality on an imported object or class. Since you're not using u, colors, grid or entity in main.py, there is no reason to import them at all.

And if you need to import them, you import them from the file where they are defined, not from objects.

In objects.py you only need to import entity from classes, and in classes you only need grid from map (btw, map is a bad name, since it shadows the internal map function).

There is no need to import symbols you don't use - you don't have to think about what the module you're importing needs; the module is responsible for that by itself.

(Another small nitpick; class names should have TitleCase, so Entity would be the correct capitalization (I'd also suggest a better class name, since Entity doesn't really say much)) (and it's True, not true).

MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • Seems I minimized too much. In the original code there's more in each file. As a result if I only import whats in a specific file, there's a module imported once per file, and u and colors being imported in two files. Is that duplicate importation bad or alright? – Adrien Levert Oct 03 '21 at 17:45
  • https://stackoverflow.com/q/37403816/14030287 the comment in the question "answered" my question and your answer directed me to that question. – Adrien Levert Oct 03 '21 at 18:10
  • 1
    It's perfectly fine; just to make sure; "will not be loaded" in the comment refers to the file being loaded from disk, the module's content will be available as expected. – MatsLindh Oct 03 '21 at 18:11