B
B
Bleno2020-01-01 22:20:59
Python
Bleno, 2020-01-01 22:20:59

How to split a project into modules?

There are 3 files:
api.py, users.py, posts.py
All names are fictitious, but reflect the meaning of this whole task. So. The api.py file has a settings class that is updated on the user's command:

class settings:
    def update(self, sql): self.settings = sql.get_settings_from_db()
settings = settings()
settings.update(sql)

It is clear that the api.py file is once imported into main.py and all the necessary variables are initialized in it, in our case, settings.
Now, if we add a couple more classes that use data from the settings class, we get something like this:
class settings:
    def update(self, sql): self.settings = sql.get_settings_from_db
class users:
    def say_id(self):
        print(settings.settings.id)
class posts:
    def do(self):
        print(settings.settings.posts)
        #code here

settings = settings()

And now, to make the code beautiful, let's break all this beauty into files:
api.py
from classes.users import users
from classes.posts import posts

class settings:
    def update(self, sql): self.settings = sql.get_settings_from_db
settings = settings()
users = users()
posts = posts()

users.say_id()

users.py
class users:
    def say_id(self):
        print(settings.settings.id)

posts.py
class posts:
    def do(self):
        print(settings.settings.posts)
        #code here

When starting api.py, problems begin (and the most interesting thing): the users class does not see the initialized settings variable in api.py, so we have trivial ways:
1. Pass settings with a function call:
users.say_id(settings)
Very simple and, in my opinion, not best option
2. Import the parent module from the users.py file: import __main__ and then __main__.settings().update()
But since settings.update() takes up resources: it connects to the database and pulls information, and if users .say_id several thousand per second, then you yourself understand, update settings 1000 times per second, which may not change for months (stupid).
To summarize
It is necessary to somehow combine all this beauty under one namespace, at the same time, so that the classes are divided into files and eventually imported into one. I hope for you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Karpion, 2020-01-02
@Karpion

Change the title of the question - it's not about that at all now.

M
Michael, 2020-01-02
@moonz

First you need to initialize the instances in the settings class.

class Settings(object):
    def __init__(self):
        self.posts = Posts()

I would generally recommend using inheritance, but it seems to be too complicated for you.
ps | In your case, the problem may be caused by an identification error, since you have variables defined in the global scope.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question