I'm exploring Python and how to structure code.
Consider the following project structure
<project root>/controllers/user_controller.py
This file then contains
class UserController:
def index():
# Something
When importing this from outside, it ends up as
import controllers.user_controller
controller_instance = controllers.user_controller.UserController()
As a Ruby developer, it feels more natural to do controllers.UserController()
or just UserController()
if the controllers folder was part of the load path, like in Rails.
Is there a (clean) way to omit the package name? I know I can do from controllers.user_controller import UserController
, but I honestly don't fancy the verbosity.
I would like to have one python file per class, but I don't want a new module for each class.
Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it's not the sole way. The import statement consists of the import keyword alongside the name of the module.
The __init__.py file indicates that the files in a folder are part of a Python package. Without an __init__.py file, you cannot import files from another directory in a Python project.
In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__ customizes the * when wildcard-importing from the package.
One way to do this is just just import the modules into the parent module. In other words imagine you have a directory structure like this:
mycoolmodule/
mycoolmodule/__init__.py
mycoolmodule/coolclass.py
mycoolmodule/coolutil.py
Code for coolclass.py:
class CoolClass:
...
Code for coolutil.py:
class CoolUtil:
...
Code for _init_.py
from coolclass import CoolClass
from coolutil import CoolUtil
Since you made them available at the package level, you can now import them directly from there. For example, this will work:
from mycoolmodule import CoolClass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With