“import *”가 나쁜 이유는 무엇입니까?
import *
파이썬 에서는 사용하지 않는 것이 좋습니다 .
누구든지 그 이유를 알려 주시면 다음에 그렇게하지 않도록 할 수 있습니까?
네임 스페이스에 많은 것들을 넣기 때문에 (이전 가져 오기에서 다른 객체를 음영 처리하고 알 수 없습니다).
정확히 무엇을 가져올 지 모르고 어떤 모듈에서 어떤 모듈을 가져 왔는지 쉽게 찾을 수 없기 때문에 (가독성).
pyflakes
코드에서 오류를 정적으로 감지하는 것과 같은 멋진 도구를 사용할 수 없기 때문 입니다.
암시적인 것보다 명시적인 것이 좋습니다.
... 논쟁 할 수 없어요?
**locals()
기능에 전달 하지 않습니까?
파이썬은 "포함"문이 부족하기 때문에 그리고self
매개 변수를 명시 적이며, 그리고 다른 모듈을 읽지 않고 어떤 종류없이 - 범위 지정 규칙은 매우 간단합니다, 그 목적은 어디에서 오는 변수에 손가락을 가리키고에게 매우 쉽게 보통이다 IDE의 (어쨌든 언어가 매우 역동적이라는 사실에 의해 조사 방법으로 제한됨).
그 import *
모든 것이 깨집니다.
또한 버그를 숨길 수도 있습니다.
import os, sys, foo, sqlalchemy, mystuff
from bar import *
이제 bar 모듈에 " os
", " mystuff
"등 ... 속성이 있으면 명시 적으로 가져온 속성을 재정의하고 매우 다른 항목을 가리킬 수 있습니다. 정의 __all__
암시 적으로 가져옵니다 무엇이 상태 - - 바에서 현명한 종종 있지만 개체를 읽고 바 모듈을 분석하고 따르지 않고, 어디에서 온 여전히 그것을 추적하기 어렵다 자사의 수입. 네트워크 import *
는 프로젝트 소유권을 가질 때 가장 먼저 수정하는 것입니다.
나를 오해하지 마십시오. 만약 import *
빠진 것이 있으면 울고 싶습니다. 그러나 신중하게 사용해야합니다. 좋은 사용 사례는 다른 모듈 위에 파사드 인터페이스를 제공하는 것입니다. 마찬가지로, 조건부 가져 오기 문을 사용하거나 함수 / 클래스 네임 스페이스 내에서 가져 오기를 사용하려면 약간의 훈련이 필요합니다.
나는 중대형 프로젝트 또는 여러 기여자가있는 작은 프로젝트에서 최소한의 pyflakes를 실행하거나 올바르게 구성된 pylint를 실행하는 정적 분석 측면에서 최소한의 위생이 필요하다고 생각합니다. 그들은 일어난다.
물론 이것은 파이썬이기 때문에 규칙을 어 기고 탐구해야합니다.하지만 소스 코드가 규율이 없으면 열 배가 될 수있는 프로젝트에주의하십시오. 문제가 될 것입니다.
네임 스페이스를 오염시키기 때문입니다. 자신의 네임 스페이스에서 모든 함수와 클래스를 가져 오며, 정의한 함수와 충돌 할 수 있습니다.
또한 유지 관리 작업에는 정규화 된 이름을 사용하는 것이 더 명확하다고 생각합니다. 코드 라인 자체에서 함수의 출처를 알 수 있으므로 문서를 훨씬 쉽게 확인할 수 있습니다.
foo 모듈에서 :
def myFunc():
print 1
귀하의 코드에서 :
from foo import *
def doThis():
myFunc() # Which myFunc is called?
def myFunc():
print 2
from ... import *
대화식 세션에서 수행해도 됩니다.
http://docs.python.org/tutorial/modules.html
일반적으로
*
모듈이나 패키지에서 가져 오는 방식은 코드를 잘 읽을 수 없기 때문에 눈살을 찌푸리게합니다 .
foo라는 모듈에 다음 코드가 있다고 가정 해보십시오.
import ElementTree as etree
그런 다음 자신의 모듈에 다음이 있습니다.
from lxml import etree
from foo import *
이제하는 어려운 디버그 모듈이 같은 모습 이 거기에 LXML의 etree을 가지고,하지만 정말 대신 ElementTree 있습니다.
이것들은 모두 좋은 대답입니다. 파이썬으로 새로운 사람들에게 코드를 작성하도록 가르 칠 때, 다루기 import *
가 매우 어렵다고 덧붙입니다. 귀하 또는 그들이 코드를 작성하지 않았더라도 여전히 걸림돌입니다.
저는 어린이 (약 8 세)에게 Minecraft를 조작하기 위해 Python으로 프로그래밍하도록 가르치고 있습니다. 나는 그들에게 ( Atom Editor )와 함께 작업하고 REPL 주도 개발 ( bpython을 통해)을 가르치는 데 도움이되는 코딩 환경을 제공하고 싶습니다 . Atom에서 힌트 / 완료가 bpython만큼 효과적으로 작동한다는 것을 알았습니다. 운 좋게도 다른 통계 분석 도구와 달리 Atom은에 속지 않습니다 import *
.
그러나,에 ... 예를 취할 수 있습니다 랩퍼이 그들이 from local_module import *
포함 무리 모듈 블록의 목록을 . 네임 스페이스 충돌의 위험을 무시합시다. 이렇게하면 from mcpi.block import *
모호한 유형의이 블록 전체 목록을 사용 가능하게 만들기 위해 살펴 봐야 할 것입니다. 대신을 사용한 경우 from mcpi import block
입력 walls = block.
하면 자동 완성 목록이 나타납니다.
사람들이 여기에 넣은 유효한 포인트를 이해했습니다. 그러나 때로는 "스타 가져 오기"가 항상 나쁜 습관은 아니라는 주장이 있습니다.
- 모든 상수가 다음과 같은 모듈로 이동하는 방식으로 코드를 구성하려는 경우
const.py
:- If I do
import const
, then for every constant, I have to refer it asconst.SOMETHING
, which is probably not the most convenient way. - If I do
from const import SOMETHING_A, SOMETHING_B ...
, then obviously it's way too verbose and defeats the purpose of the structuring. - Thus I feel in this case, doing a
from const import *
may be a better choice.
- If I do
It is a very BAD practice for two reasons:
- Code Readability
- Risk of overriding the variables/functions etc
For point 1: Let's see an example of this:
from module1 import *
from module2 import *
from module3 import *
a = b + c - d
Here, on seeing the code no one will get idea regarding from which module b
, c
and d
actually belongs.
On the other way, if you do it like:
# v v will know that these are from module1
from module1 import b, c # way 1
import module2 # way 2
a = b + c - module2.d
# ^ will know it is from module2
It is much cleaner for you, and also the new person joining your team will have better idea.
For point 2: Let say both module1
and module2
have variable as b
. When I do:
from module1 import *
from module2 import *
print b # will print the value from module2
Here the value from module1
is lost. It will be hard to debug why the code is not working even if b
is declared in module1
and I have written the code expecting my code to use module1.b
If you have same variables in different modules, and you do not want to import entire module, you may even do:
from module1 import b as mod1b
from module2 import b as mod2b
As a test, I created a module test.py with 2 functions A and B, which respectively print "A 1" and "B 1". After importing test.py with:
import test
. . . I can run the 2 functions as test.A() and test.B(), and "test" shows up as a module in the namespace, so if I edit test.py I can reload it with:
import importlib
importlib.reload(test)
But if I do the following:
from test import *
there is no reference to "test" in the namespace, so there is no way to reload it after an edit (as far as I can tell), which is a problem in an interactive session. Whereas either of the following:
import test
import test as tt
will add "test" or "tt" (respectively) as module names in the namespace, which will allow re-loading.
If I do:
from test import *
the names "A" and "B" show up in the namespace as functions. If I edit test.py, and repeat the above command, the modified versions of the functions do not get reloaded.
And the following command elicits an error message.
importlib.reload(test) # Error - name 'test' is not defined
If someone knows how to reload a module loaded with "from module import *", please post. Otherwise, this would be another reason to avoid the form:
from module import *
As suggested in the docs, you should never use import *
in production code.
While importing *
from a module is bad, importing * from a package is even worse. Basically, from package import *
imports whatever names are defined by the package's __init__.py
, but it also includes any submodules of the package that were loaded by previous import
statements.
Consider this example:
# anywhere in the code before import *
import sound.effects.echo
import sound.effects.surround
# in your module
from sound.effects import *
The last statement will import the echo
and surround
modules into the current namespace (possibly overriding previous definitions) because they are defined in the sound.effects
package when the import
statement is executed.
참고URL : https://stackoverflow.com/questions/2386714/why-is-import-bad
'Programing' 카테고리의 다른 글
Intellij Idea Project Tool Window에서 현재 클래스로 자동 탐색하는 방법은 무엇입니까? (0) | 2020.06.29 |
---|---|
Java로 날짜에 n 시간을 추가 하시겠습니까? (0) | 2020.06.29 |
CSS를 사용하여 ul 들여 쓰기 제거 (0) | 2020.06.28 |
C ++ 재정의 헤더 파일 (winsock2.h) (0) | 2020.06.28 |
NodeJS는 글로벌 모듈 / 패키지를 필요로합니다 (0) | 2020.06.28 |