I am confused how directory name, file name and class name all work together.
This is what I have at the moment
app.py database/ client.py staff.py order.py
Inside client.py I have a single class called client, which acts as the database model (MVC). The same with my other files: staff.py has a class called staff, order.py has order.
Then in app.py I do:
from database import client as model c = model.client()
And then I get confused. In an ideal world this is what I want to do:
-
Keep my database model classes in separate files in their own directory.
-
Use them like this:
c = model.client() o = model.order() s = model.staff()
The only way I can see to do this is to put all my classes in a single file called model.py and save this at the root.
I’m sure I am missing something very basic here.
Python has two basic ways of importing content. Modules and Packages.
A module is simply a python file on the include path: order.py
If order.py defines a class named foo, then access to that class could be had by:
In order to use the syntax from the orignial question, you would need to ensure that your model.py file has the following attributes: [client, staff, order]
However, that typically means placing them in a single file. Which is what you are trying to avoid.
A package is a directory with an __init__.py inside of it. The init.py initializes the package (ie. it is run on first import), and you can have either modules or sub-packages within that directory.
That way, to access any of the sub modules, you would simply say:
However, that is simply importing the module. It is not importing any of the attributes of the module. So in order to access a class inside the module, you would need to specify it:
This is a bit tedious, but very well organized.
Best of both (where performance isn’t a big deal):
If you type the following code in __init__.py:
Then you have auto-loaded all of your classes, and they can be accessed as:
In the end, it may be more simple to stick with the non-magical way to do it:
–Gahooa