내부 함수를 가져 오는 것은 파이썬입니까?
PEP 8의 말 :
- 가져 오기는 항상 파일의 맨 위에, 모듈 주석 및 문서 문자열 바로 다음과 모듈 전역 및 상수 바로 앞에 배치됩니다.
occation에서 PEP 8을 위반합니다. 때로는 함수 내부에서 항목을 가져옵니다. 일반적으로 단일 함수 내에서만 사용되는 가져 오기가있는 경우이 작업을 수행합니다.
의견이 있습니까?
편집 (함수로 가져 오는 느낌이 좋은 아이디어 일 수 있음) :
주요 이유 : 코드를 더 명확하게 만들 수 있습니다.
- 함수의 코드를 볼 때 "함수 / 클래스 xxx 란 무엇입니까?" (xxx는 함수 내에서 사용됨). 모듈 상단에 모든 수입품이 있으면 xxx가 무엇인지 확인하기 위해 가야합니다. 를 사용할 때 더 많은 문제가
from m import xxx
있습니다.m.xxx
이 기능을 보면 더 많은 것을 알 수 있습니다. 무엇에 따라m
: 잘 알려진 최상위 모듈 / 패키지 (import m
)입니까? 아니면 하위 모듈 / 패키지 (from a.b.c import m
)입니까? - 경우에 따라 xxx가 사용되는 위치에 추가 정보 ( "xxx 란 무엇입니까?")가 있으면 함수를보다 쉽게 이해할 수 있습니다.
장기적으로는 파일 상단에 대부분의 가져 오기를 가져와 주셔서 감사합니다. 그러면 모듈이 가져 오기로 인해 얼마나 복잡한 지 한눈에 알 수 있습니다.
기존 파일에 새 코드를 추가하는 경우 일반적으로 필요한 곳에서 가져 오기를 수행 한 다음 코드가 유지되는 경우 가져 오기 줄을 파일 맨 위로 이동하여 작업을 더 영구적으로 만듭니다.
또 다른 요점 ImportError
은 코드를 실행하기 전에 예외를 확인하는 것입니다. 온 전성 검사로 맨 위에 가져 오는 또 다른 이유입니다.
사용 pyChecker
하지 않는 모듈을 확인하는 데 사용합니다.
이와 관련하여 PEP 8을 위반 한 경우는 두 가지입니다.
- 순환 가져 오기 : 모듈 A는 모듈 B를 가져 오지만 모듈 B의 항목에는 모듈 A가 필요합니다 (이것은 종종 순환 종속성을 제거하기 위해 모듈을 리팩터링해야한다는 신호입니다)
- pdb 중단 점 삽입 :
import pdb; pdb.set_trace()
이것은import pdb
디버그 할 수있는 모든 모듈의 상단에 놓고 싶지 않은 편리한 b / c이며 중단 점 을 제거 할 때 가져 오기를 제거하는 것을 쉽게 기억합니다.
이 두 가지 경우를 제외하고 모든 것을 맨 위에 두는 것이 좋습니다. 종속성을 더 명확하게 만듭니다.
다음은 우리가 사용하는 네 가지 가져 오기 사용 사례입니다.
import
(그리고from x import y
하고import x as y
) 상단가져 오기 선택. 상단에.
import settings if setting.something: import this as foo else: import that as foo
조건부 가져 오기. JSON, XML 라이브러리 등과 함께 사용됩니다. 상단에.
try: import this as foo except ImportError: import that as foo
동적 가져 오기. 지금까지 우리는 이것의 한 가지 예만을 가지고 있습니다.
import settings module_stuff = {} module= __import__( settings.some_module, module_stuff ) x = module_stuff['x']
이 동적 가져 오기는 코드를 가져 오는 것이 아니라 Python으로 작성된 복잡한 데이터 구조를 가져옵니다. 직접 손으로 절인 것을 제외하고는 절인 데이터 조각과 같습니다.
이것은 또한 모듈의 맨 위에 있습니다.
Here's what we do to make the code clearer:
Keep the modules short.
If I have all my imports at the top of the module, I have to go look there to determine what a name is. If the module is short, that's easy to do.
In some cases having that extra information close to where a name is used can make the function easier to understand. If the module is short, that's easy to do.
One thing to bear in mind: needless imports can cause performance problems. So if this is a function that will be called frequently, you're better off just putting the import at the top. Of course this is an optimization, so if there's a valid case to be made that importing inside a function is more clear than importing at the top of a file, that trumps performance in most cases.
If you're doing IronPython, I'm told that it's better to import inside functions (since compiling code in IronPython can be slow). Thus, you may be able to get a way with importing inside functions then. But other than that, I'd argue that it's just not worth it to fight convention.
As a general rule, I do this if there is an import that is only used within a single function.
Another point I'd like to make is that this may be a potential maintenence problem. What happens if you add a function that uses a module that was previously used by only one function? Are you going to remember to add the import to the top of the file? Or are you going to scan each and every function for imports?
FWIW, there are cases where it makes sense to import inside a function. For example, if you want to set the language in cx_Oracle, you need to set an NLS_
LANG environment variable before it is imported. Thus, you may see code like this:
import os
oracle = None
def InitializeOracle(lang):
global oracle
os.environ['NLS_LANG'] = lang
import cx_Oracle
oracle = cx_Oracle
I've broken this rule before for modules that are self-testing. That is, they are normally just used for support, but I define a main for them so that if you run them by themselves you can test their functionality. In that case I sometimes import getopt
and cmd
just in main, because I want it to be clear to someone reading the code that these modules have nothing to do with the normal operation of the module and are only being included for testing.
Coming from the question about loading the module twice - Why not both?
An import at the top of the script will indicate the dependencies and another import in the function with make this function more atomic, while seemingly not causing any performance disadvantage, since a consecutive import is cheap.
As long as it's import
and not from x import *
, you should put them at the top. It adds just one name to the global namespace, and you stick to PEP 8. Plus, if you later need it somewhere else, you don't have to move anything around.
It's no big deal, but since there's almost no difference I'd suggest doing what PEP 8 says.
Have a look at the alternative approach that's used in sqlalchemy: dependency injection:
@util.dependencies("sqlalchemy.orm.query")
def merge_result(query, *args):
#...
query.Query(...)
Notice how the imported library is declared in a decorator, and passed as an argument to the function!
This approach makes the code cleaner, and also works 4.5 times faster than an import
statement!
Benchmark: https://gist.github.com/kolypto/589e84fbcfb6312532658df2fabdb796
In modules that are both 'normal' modules and can be executed (i.e. have a if __name__ == '__main__':
-section), I usually import modules that are only used when executing the module inside the main section.
Example:
def really_useful_function(data):
...
def main():
from pathlib import Path
from argparse import ArgumentParser
from dataloader import load_data_from_directory
parser = ArgumentParser()
parser.add_argument('directory')
args = parser.parse_args()
data = load_data_from_directory(Path(args.directory))
print(really_useful_function(data)
if __name__ == '__main__':
main()
참고URL : https://stackoverflow.com/questions/1024049/is-it-pythonic-to-import-inside-functions
'IT story' 카테고리의 다른 글
Github에서 풀 요청을 기본값과 다른 브랜치로 병합 (0) | 2020.08.06 |
---|---|
CORS를 악용하기 위해 악성 코드가 "Origin"헤더를 스푸핑하는 것을 막는 것은 무엇입니까? (0) | 2020.08.06 |
Java 스트림에서 flush ()의 목적은 무엇입니까? (0) | 2020.08.06 |
기본 저장소를 설정하는 방법 (0) | 2020.08.06 |
한 지역 지점을 다른 지역 지점으로 병합 (0) | 2020.08.06 |