Home > other >  How to write python code to be split into multiple files?
How to write python code to be split into multiple files?

Time:10-04

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)

CodePudding user response:

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).

  • Related