Python에서 모듈 가져 오기-모범 사례
R을 사용하여 배운 기술을 확장하고 싶기 때문에 Python을 처음 사용합니다. RI에서는 여러 라이브러리를로드하는 경향이있어 때때로 함수 이름 충돌이 발생합니다.
Python에서 모범 사례는 무엇입니까? 나는 차이점이 보이지 않는 특정 변형을 보았습니다.
import pandas
, from pandas import *
및from pandas import DataFrame
처음 두 가지의 차이점은 무엇이며 필요한 것을 가져와야합니다. 또한 데이터를 처리하고 간단한 통계를 계산하기 위해 작은 프로그램을 만드는 사람에게 최악의 결과는 무엇일까요?
최신 정보
이 훌륭한 가이드를 찾았습니다 . 그것은 모든 것을 설명합니다.
import pandas
pandas 네임 스페이스 아래에 pandas 모듈을 가져 오므로 pandas.foo
.
from pandas import *
pandas 모듈의 모든 객체를 현재 네임 스페이스로 가져 오므로 foo
. 현재 네임 스페이스와 pandas 네임 스페이스 사이에 이름 지정 충돌이있는 경우 예외가없는 결과를 초래할 수 있습니다.
from pandas import DataFrame
위와 동일하지만 DataFrame
(모든 것이 아닌) 현재 네임 스페이스 로만 가져옵니다 .
제 생각에 첫 번째는 일반적으로 가장 좋은 방법입니다. 다른 모듈을 코드에서 잘 구분하여 유지하기 때문입니다.
각 형태의 단점
다른 사람의 코드를 읽을 때 (그리고 그 사람들은 매우 다른 가져 오기 스타일을 사용함) 각 스타일에서 다음과 같은 문제를 발견했습니다.
import modulewithaverylongname
긴 모듈 이름 (예 : concurrent.futures
또는 django.contrib.auth.backends
)으로 코드를 더 복잡하게 만들고 해당 위치에서 가독성을 떨어 뜨립니다 .
from module import *
나에게 예를 들어, 구문이 참조 할 기회를 부여하지 않습니다 classA
와 classB
같은 모듈에서들이 서로 함께 할 수있는 여지가 있습니다. 그것은 코드를 읽을 수 있습니다 하드 . (이러한 가져 오기의 이름은 이전 가져 오기의 이름을 그림자로 만들 수 있습니다.
from module import classA, classB, functionC, constantD, functionE
module
코드를 일관되게 이해하기 위해 정신적으로 할당해야하는 너무 많은 이름으로 단기 기억에 과부하 가 걸립니다.
import modulewithaverylongname as mwvln
때로는 나에게 충분하지 않은 니모닉 입니다.
적절한 타협
위의 관찰을 바탕으로 내 코드에서 다음 스타일을 개발했습니다.
import module
표준 라이브러리에있는 대부분의 패키지와 같이 모듈 이름이 짧은 경우 선호되는 스타일입니다. 또한 모듈의 이름을 내 모듈의 2 ~ 3 곳에서만 사용해야하는 경우 선호되는 스타일입니다. 명확성이 간결함보다 우선합니다 ( "가독성이 중요합니다" ).
import longername as ln
거의 모든 경우에서 선호되는 스타일입니다. 예를 들어, 나는 import django.contrib.auth.backends as dj_abe
. 위의 기준 1의 정의에 따라 약어가 자주 사용되므로 쉽게 기억할 수 있습니다.
"명시적인 것이 암시적인 것보다 낫다"에 따라이 두 가지 스타일 만이 완전히 파이썬 적입니다. 규칙.
from module import xx
내 코드에서 가끔 발생합니다. as
형식 조차 과장된 것처럼 보이는 경우에 사용합니다 from datetime import datetime
. 가장 유명한 예는 .
일반적으로 명시 적 가져 오기를 수행하는 것이 좋습니다. 에서와 같이 :
import pandas
frame = pandas.DataFrame()
또는:
from pandas import DataFrame
frame = DataFrame()
Python의 또 다른 옵션은 이름이 충돌 할 때 x를 y로 가져 오는 것입니다.
from pandas import DataFrame as PDataFrame
from bears import DataFrame as BDataFrame
frame1 = PDataFrame()
frame2 = BDataFrame()
다음은 PEP8 스타일 가이드의 몇 가지 권장 사항입니다 .
가져 오기는 일반적으로 별도의 행에 있어야합니다 . 예 :
Yes: import os import sys No: import sys, os
하지만 괜찮아
from subprocess import Popen, PIPE
가져 오기는 항상 파일의 맨 위에, 모듈 주석과 독 스트링 바로 뒤, 모듈 전역과 상수 앞에 놓입니다.
- 가져 오기는 다음 순서로 그룹화되어야합니다.
- 표준 라이브러리 가져 오기
- 관련 제 3 자 수입
- 로컬 애플리케이션 / 라이브러리 특정 가져 오기
- 각 수입품 그룹 사이에 빈 줄을 넣어야합니다.
- 가져 오기는 다음 순서로 그룹화되어야합니다.
절대 가져 오기를 권장
합니다. 가져 오기 시스템을 엉망으로 만들 경우 더 나은 오류 메시지를 제공하여 더 읽기 쉽고 디버깅이 더 쉽습니다.import mypkg.sibling from mypkg import sibling from mypkg.sibling import example
또는 명시 적 상대적 수입
from . import sibling from .sibling import example
Implicit relative imports should never be used and is removed in Python 3.
No: from ..grand_parent_package import uncle_package
Wildcard imports (
from <module> import *
) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools.
Some recommendations about lazy imports
from python speed performance tips.
Import Statement Overhead
import statements can be executed just about anywhere. It's often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python's interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement can seriously affect performance in some circumstances.
the given below is a scenario explained at the page,
>>> def doit1():
... import string
... string.lower('Python')
...
>>> import string
>>> def doit2():
... string.lower('Python')
...
>>> import timeit
>>> t = timeit.Timer(setup='from __main__ import doit1', stmt='doit1()')
>>> t.timeit()
11.479144930839539
>>> t = timeit.Timer(setup='from __main__ import doit2', stmt='doit2()')
>>> t.timeit()
4.6661689281463623
from A import B
essentially equals following three statements
import A
B = A.B
del A
That's it, that is it all.
They are all suitable in different contexts (which is why they are all available). There's no deep guiding principle, other than generic motherhood statements around clarity, maintainability and simplicity. Some examples from my own code:
import sys, os, re, itertools
avoids name collisions and provides a very succinct way to import a bunch of standard modules.from math import *
lets me writesin(x)
instead ofmath.sin(x)
in math-heavy code. This gets a bit dicey when I also import numpy, which doubles up on some of these, but it doesn't overly concern me, since they are generally the same functions anyway. Also, I tend to follow the numpy documentation —import numpy as np
— which sidesteps the issue entirely.- I favour
from PIL import Image, ImageDraw
just because that's the way the PIL documentation presents its examples.
참고URL : https://stackoverflow.com/questions/9916878/importing-modules-in-python-best-practice
'Development Tip' 카테고리의 다른 글
부동 소수점 값을 변환 할 때 std :: to_string의 정밀도 설정 (0) | 2020.12.08 |
---|---|
파이썬에서 목록을 jsonarray로 변환하는 방법 (0) | 2020.12.08 |
Windows Phone 8 에뮬레이터 오류-스위치를 만드는 동안 문제가 발생했습니다. (0) | 2020.12.07 |
내 사용자 정의보기에서 표준 속성 android : text를 사용하는 방법은 무엇입니까? (0) | 2020.12.07 |
Glob 일치, 모든 JS 파일 제외 (0) | 2020.12.07 |