Niels B.
Niels B.

Reputation: 6310

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.

Upvotes: 31

Views: 51539

Answers (2)

maybe you should rely on relative path, as suggested by the above post by Ryan Widmaier, but:

Code for init.py

from .coolclass import CoolClass
from .coolutil import CoolUtil

Upvotes: 8

Ryan Widmaier
Ryan Widmaier

Reputation: 8513

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

Upvotes: 48

Related Questions