简体   繁体   English

Pythonic编写长导入语句的方法

[英]Pythonic way to write long import statements

What is the pythonic way to import from Models (or Forms or views) in Django? 什么是从Django中的模型(或表单或视图)导入的pythonic方法?

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? 它远远超过最多79个字符 - 但更好的方法是什么?

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 : 这符合PEP-328括号的基本原理

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语句:

( import * is not an option ;-) import *不是一种选择;-)

Instead, it should be possible to use Python's standard grouping mechanism (parentheses) to write the import statement: 相反,应该可以使用Python的标准分组机制(括号)来编写import语句:

This part of the proposal had BDFL approval from the beginning. 这部分提案从一开始就获得了BDFL的批准。

Parentheses support was added to Python 2.4. Python 2.4中添加了括号支持。

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 您还可以拥有一个名称空间,并且可以使用名为foobar局部变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM