Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to write long import statements

What is the pythonic way to import from Models (or Forms or views) in Django?

To say it frank I bluntly do this:

from myapp.models import foo, bar, foobar, barfoo, foofoo, barbar, barfoobar, thelistgoeson, and, on, andon...

It is far longer than the maximum of 79 characters - but what is the better way to do this?

like image 632
Maximilian Kindshofer Avatar asked Apr 20 '26 11:04

Maximilian Kindshofer


2 Answers

Use parentheses to group your imports together:

from myapp.models import (foo, bar, foobar, barfoo, foofoo,
    barbar, barfoobar, thelistgoeson, and, on, and, so, on)

This is in accordance with PEP-328 Rationale for parentheses:

Currently, if you want to import a lot of names from a module or package, you have to choose one of several unpalatable options:

  • Write a long line with backslash continuations:
  • Write multiple import statements:

(import * is not an option ;-)

Instead, it should be possible to use Python's standard grouping mechanism (parentheses) to write the import statement:

This part of the proposal had BDFL approval from the beginning.

Parentheses support was added to Python 2.4.

like image 163
Anshul Goyal Avatar answered Apr 22 '26 01:04

Anshul Goyal


What about importing models?

from myapp import models

foo = models.foo
bar = models.bar

It is much shorter and you don't have to maintain a list of imports. You also get to have a namespace, and you can have local variables called foo and bar

like image 22
Paco Avatar answered Apr 21 '26 23:04

Paco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!