Python 가져 오기에 대한 좋은 경험 규칙은 무엇입니까?
Python에서 모듈을 가져올 수있는 다양한 방법에 대해 약간 혼란스러워합니다.
import X
import X as Y
from A import B
범위 지정 및 네임 스페이스에 대해 읽어 봤지만 어떤 상황에서 왜 가장 좋은 전략인지에 대한 실질적인 조언을 원합니다. 모듈 수준 또는 메서드 / 기능 수준에서 가져 오기가 발생해야합니까? 에서 __init__.py
또는 모듈 코드 자체에?
내 질문은 " Python packages-import by class, not file " 에 의해 실제로 답변되지는 않지만 분명히 관련되어 있습니다.
우리 회사의 프로덕션 코드에서는 다음 규칙을 따르려고 노력합니다.
파일의 시작 부분, 메인 파일의 독 스트링 바로 뒤에 가져 오기를 배치합니다. 예 :
"""
Registry related functionality.
"""
import wx
# ...
이제 가져온 모듈에서 몇 안되는 클래스 중 하나를 가져 오면 이름을 직접 가져 오므로 코드에서 마지막 부분 만 사용하면됩니다. 예 :
from RegistryController import RegistryController
from ui.windows.lists import ListCtrl, DynamicListCtrl
그러나 가능한 모든 예외 목록과 같이 수십 개의 클래스를 포함하는 모듈이 있습니다. 그런 다음 모듈 자체를 가져와 코드에서 참조합니다.
from main.core import Exceptions
# ...
raise Exceptions.FileNotFound()
import X as Y
특정 모듈이나 클래스의 사용을 검색하기 어렵 기 때문에 가능한 한 드물게 사용합니다 . 그러나 때로는 이름이 같지만 다른 모듈에 존재하는 두 클래스를 가져 오려면이를 사용해야합니다. 예 :
from Queue import Queue
from main.core.MessageQueue import Queue as MessageQueue
일반적으로 메서드 내에서 가져 오기를 수행하지 않습니다. 단순히 코드를 느리고 읽기 어렵게 만듭니다. 일부 사람들은 이것이 주기적 가져 오기 문제를 쉽게 해결하는 좋은 방법이라고 생각할 수 있지만 더 나은 해결책은 코드 재구성입니다.
Guido van Rossum이 시작한 django-dev 메일 링리스트에 대화의 일부를 붙여 넣겠습니다.
[...] 예를 들어, 모든 가져 오기가 해당 모듈의 클래스 나 함수가 아닌 모듈을 가져와야한다는 것은 Google Python 스타일 가이드 [1]의 일부입니다. 모듈보다 더 많은 클래스와 함수가 있으므로 모듈 이름이 접두사로 붙어 있으면 특정 항목의 출처를 기억하는 것이 훨씬 쉽습니다. 종종 여러 모듈이 동일한 이름을 가진 것을 정의하기 위해 발생합니다. 따라서 코드를 읽는 사람은 주어진 이름을 가져온 모듈을보기 위해 파일의 맨 위로 돌아갈 필요가 없습니다.
출처 : http://groups.google.com/group/django-developers/browse_thread/thread/78975372cdfb7d1a
1 : http://code.google.com/p/soc/wiki/PythonStyleGuide#Module_and_package_imports
나는 일반적 import X
으로 모듈 수준에서 사용 합니다. 모듈에서 단일 객체 만 필요한 경우 from X import Y
.
import X as Y
이름 충돌이 발생하는 경우 에만 사용하십시오 .
모듈이 기본 모듈로 사용될 때 필요한 것을 가져 오기 위해 함수 수준에서만 가져 오기를 사용합니다.
def main():
import sys
if len(sys.argv) > 1:
pass
HTH
위의 누군가가
from X import A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P
다음과 같다
import X
import X
AP에 대한 직접 수정을 허용하고 AP의 from X import ...
사본 을 생성합니다. 들어 from X import A..P
당신이 변수에 대한 업데이트를하지 않는 그들은 수정합니다. 수정하면 사본 만 수정하지만 X는 수정 사항에 대해 알고 있습니다.
AP가 기능이라면 차이점을 알 수 없습니다.
다른 사람들은 여기서 대부분의 부분을 다루었지만 import X as Y
새로운 버전의 클래스 또는 모듈을 시험 할 때 (일시적으로) 사용할 한 가지 사례를 추가하고 싶었습니다 .
따라서 모듈의 새로운 구현으로 마이그레이션했지만 한 번에 코드베이스를 모두 자르고 싶지 않은 경우, xyz_new
모듈을 작성하고 마이그레이션 한 소스 파일에서이를 수행 할 수 있습니다 .
import xyz_new as xyz
그런 다음 전체 코드베이스를 잘라 내면 xyz
모듈을 다음으로 교체하고 xyz_new
모든 가져 오기를 다시
import xyz
이렇게하지 마십시오 :
from X import *
해당 모듈의 모든 것을 사용할 것이라는 확신이 없다면. 그런 다음에도 다른 접근 방식을 사용하여 재고해야합니다.
그 외에는 스타일 문제 일뿐입니다.
from X import Y
좋으며 많은 타이핑을 절약 할 수 있습니다. 나는 그것을 꽤 자주 사용할 때 그것을 사용하는 경향이 있지만 그 모듈에서 많은 것을 가져 오는 경우 다음과 같은 import 문으로 끝날 수 있습니다.
from X import A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P
당신은 아이디어를 얻습니다. 그때 수입품이
import X
유용 해집니다. 또는 X에서 자주 사용하지 않는 경우.
일반적으로 import modulename
모듈 이름이 길거나 자주 사용되지 않는 한 regular을 사용하려고합니다 .
예를 들어 ..
from BeautifulSoup import BeautifulStoneSoup as BSS
.. 그래서 soup = BSS(html)
대신 할 수 있습니다BeautifulSoup.BeautifulStoneSoup(html)
또는..
from xmpp import XmppClientBase
..XmppClientBase 만 사용할 때 xmpp 전체를 가져 오는 대신
import x as y
매우 긴 메서드 이름을 가져 오거나 기존 가져 오기 / 변수 / 클래스 / 메서드를 방해하지 않으려면 사용하면 편리합니다 (완전히 피해야하지만 항상 가능한 것은 아닙니다).
Say I want to run a main() function from another script, but I already have a main() function..
from my_other_module import main as other_module_main
..wouldn't replace my main
function with my_other_module's main
Oh, one thing - don't do from x import *
- it makes your code very hard to understand, as you cannot easily see where a method came from (from x import *; from y import *; my_func()
- where is my_func defined?)
In all cases, you could just do import modulename
and then do modulename.subthing1.subthing2.method("test")
...
The from x import y as z
stuff is purely for convenience - use it whenever it'll make your code easier to read or write!
When you have a well-written library, which is sometimes case in python, you ought just import it and use it as it. Well-written library tends to take life and language of its own, resulting in pleasant-to-read -code, where you rarely reference the library. When a library is well-written, you ought not need renaming or anything else too often.
import gat
node = gat.Node()
child = node.children()
Sometimes it's not possible to write it this way, or then you want to lift down things from library you imported.
from gat import Node, SubNode
node = Node()
child = SubNode(node)
Sometimes you do this for lot of things, if your import string overflows 80 columns, It's good idea to do this:
from gat import (
Node, SubNode, TopNode, SuperNode, CoolNode,
PowerNode, UpNode
)
The best strategy is to keep all of these imports on the top of the file. Preferrably ordered alphabetically, import -statements first, then from import -statements.
Now I tell you why this is the best convention.
Python could perfectly have had an automatic import, which'd look from the main imports for the value when it can't be found from global namespace. But this is not a good idea. I explain shortly why. Aside it being more complicated to implement than simple import, programmers wouldn't be so much thinking about the depedencies and finding out from where you imported things ought be done some other way than just looking into imports.
Need to find out depedencies is one reason why people hate "from ... import *". Some bad examples where you need to do this exist though, for example opengl -wrappings.
So the import definitions are actually valuable as defining the depedencies of the program. It is the way how you should exploit them. From them you can quickly just check where some weird function is imported from.
The import X as Y
is useful if you have different implementations of the same module/class.
With some nested try..import..except ImportError..import
s you can hide the implementation from your code. See lxml etree import example:
try:
from lxml import etree
print("running with lxml.etree")
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as etree
print("running with cElementTree on Python 2.5+")
except ImportError:
try:
# Python 2.5
import xml.etree.ElementTree as etree
print("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree
print("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree
print("running with ElementTree")
except ImportError:
print("Failed to import ElementTree from any known place")
I'm with Jason in the fact of not using
from X import *
But in my case (i'm not an expert programmer, so my code does not meet the coding style too well) I usually do in my programs a file with all the constants like program version, authors, error messages and all that stuff, so the file are just definitions, then I make the import
from const import *
That saves me a lot of time. But it's the only file that has that import, and it's because all inside that file are just variable declarations.
Doing that kind of import in a file with classes and definitions might be useful, but when you have to read that code you spend lots of time locating functions and classes.
참고URL : https://stackoverflow.com/questions/193919/what-are-good-rules-of-thumb-for-python-imports
'Nice programing' 카테고리의 다른 글
dplyr 파이프에서 NA 제거 (0) | 2020.10.29 |
---|---|
VS Code에서 기본적으로 텍스트 줄 바꿈을 설정하는 방법 (0) | 2020.10.29 |
딥 클론 유틸리티 권장 사항 (0) | 2020.10.29 |
MS Excel 용 JSON 형식을 CSV 형식으로 변환 (0) | 2020.10.29 |
데이터 주석의 Asp.Net Mvc 숨겨진 필드 (0) | 2020.10.29 |