Default Export in Python 3

In the project I'm working on, I split a lot of large files into smaller parts to make it easier to work with. One specific example is creating classes based views from functions 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, not the method from the module, although they have the same name. Ideally, I would like to call LoginView.LoginView every time.

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

Is there a way to do something like this in Python 3? I don’t want to do from app.views.LoginView import LoginView , because, especially in a large Django project and in a file like urls.py , it is not possible to import each on a separate line.

+5
source share
1 answer

You can import LoginView as a name in app.views using __init__.py from 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()) ] 
+4
source

All Articles