Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default export in Python 3

In a project I'm working on, I'm separating a lot of bigger files into smaller pieces so they're easier to work with. One specific example is creating class based views from function based views in Django:

# app/views/LoginView.py
class LoginView(View):
  ...

# urls.py
from app.views import LoginView
urlpatterns = [
  # Here, I have to use LoginView twice
  url(r'^login', LoginView.LoginView.as_view())
]

Above, I have to use LoginView twice when I want to call it, since importing LoginView imports the module, and not the method from the module, even though they are the same name. Ideally, I'd like to avoid having to call LoginView.LoginView each time.

In Javascript, I can just say export default function my_function() { ... } without naming it, and when it's imported it's default, e.g import my_function from './some_module.js';

Is there any way to do something like this in Python 3? I do not want to do from app.views.LoginView import LoginView because, especially in a big Django project and in a file like urls.py, it isn't feasible to have each import on a separate line.

like image 201
josh Avatar asked Aug 13 '16 00:08

josh


1 Answers

You can import LoginView as a name under app.views using the __init__.py of app.views.

In app/views/__init__.py:

from LoginView import LoginView

In urls.py

import app.views 

urlpatterns = [
    url(r'^login', app.views.LoginView.as_view())
]
like image 67
OregonTrail Avatar answered Oct 04 '22 05:10

OregonTrail