'Expose/export class instead of module from python file
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.
Solution 1:[1]
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(object):
...
Code for coolutil.py:
class CoolUtil(object):
...
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Remco Haszing |