24

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.

2
  • Do you have quarrel with import controllers.user_controller as ctrl?
    – pstatix
    Apr 6, 2018 at 13:40
  • 1
    Yes, I don't think ctrl.UserController() reads well.
    – Niels B.
    Apr 6, 2018 at 13:43

2 Answers 2

39

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
3
  • 2
    In my __init__.py it says ModuleNotFoundError: No module named 'coolclass', even though I think I did everything correctly.
    – Seangle
    Oct 4, 2022 at 5:51
  • Hard to say w/o seeing exactly what you are doing, but the above example should work. Oct 5, 2022 at 13:17
  • I think _init_.py should contain .coolclass instead of coolclass and .coolutil instad of coolutil respectively. Otherwise it doesn't work properly due to circular dependencies.
    – I.R.
    Mar 20 at 12:30
4

maybe you should rely on relative path, like this enter link description here, but:

Code for init.py

from .coolclass import CoolClass
from .coolutil import CoolUtil

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.