IT Share you

Python의 좋은 습관 또는 나쁜 습관 : 파일 중간에 가져 오기

shareyou 2021. 1. 6. 08:08
반응형

Python의 좋은 습관 또는 나쁜 습관 : 파일 중간에 가져 오기


비교적 긴 모듈이 있지만 외부 모듈이나 메서드가 한 번만 필요하다고 가정합니다.

모듈 중간에 해당 메서드 또는 모듈을 가져 오는 것이 괜찮습니까?

또는 imports는 모듈의 첫 번째 부분에만 있어야 합니다.

예:

import string, pythis, pythat
...
...
...
...
def func():
     blah
     blah 
     blah
     from pysomething import foo
     foo()
     etc
     etc 
     etc
...
...
...

답변을 정당화하고 PEP 또는 관련 소스에 대한 링크를 추가하십시오.


PEP 8 은 다음과 같이 정식으로 진술합니다.

가져 오기는 항상 파일의 맨 위에, 모듈 주석 및 독 스트링 바로 뒤, 모듈 전역 및 상수 앞에 놓입니다.

PEP 8은 모든 "사내"스타일 가이드의 기초가되어야합니다. 이는 핵심 Python 팀이 전체적으로 가장 효과적인 스타일이라고 판단한 내용을 요약하기 때문입니다. BDFL은 PEP 8)에 동의합니다.


2001 년에 Python 메일 링리스트에이 주제에 대한 자세한 논의가있었습니다.

https://mail.python.org/pipermail/python-list/2001-July/071567.html


다른 사람들은 이미 PEP에 대해 언급했지만 중요한 코드 중간에 import 문 없도록 주의해야 합니다. 적어도 Python 2.6에서는 함수에 import 문이있을 때 필요한 바이트 코드 명령어가 몇 가지 더 있습니다.

>>> def f():
    from time import time
    print time()

>>> dis.dis(f)
  2           0 LOAD_CONST               1 (-1)
              3 LOAD_CONST               2 (('time',))
              6 IMPORT_NAME              0 (time)
              9 IMPORT_FROM              0 (time)
             12 STORE_FAST               0 (time)
             15 POP_TOP             

  3          16 LOAD_FAST                0 (time)
             19 CALL_FUNCTION            0
             22 PRINT_ITEM          
             23 PRINT_NEWLINE       
             24 LOAD_CONST               0 (None)
             27 RETURN_VALUE

>>> def g():
    print time()

>>> dis.dis(g)
  2           0 LOAD_GLOBAL              0 (time)
              3 CALL_FUNCTION            0
              6 PRINT_ITEM          
              7 PRINT_NEWLINE       
              8 LOAD_CONST               0 (None)
             11 RETURN_VALUE  

가져온 모듈이 자주 사용되지 않고 가져 오기 비용이 많이 드는 경우 중간 가져 오기는 괜찮습니다.

Otherwise, is it wise to follow Alex Martelli's suggestion.


It's generally considered bad practice, but sometimes it's unavoidable (say when you have to avoid a circular import).

An example of a time when it is necessary: I use Waf to build all our code. The system is split into tools, and each tool is implemented in it's own module. Each tool module can implent a detect() method to detect if the pre-requisites are present. An example of one of these may do the following:

def detect(self):
    import foobar

If this works correctly, the tool is usable. Then later in the same module the foobar module may be needed, so you would have to import it again, at function level scope. Clearly if it was imported at module level things would blow up completely.


It is considered "Good Form" to group all imports together at the start of the file.

Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global symbol table.

From here: http://docs.python.org/tutorial/modules.html


95% of the time, you should put all your imports at the top of the file. One case where you might want to do a function-local import is if you have to do it in order to avoid circular imports. Say foo.py imports bar.py, and a function in bar.py needs to import something from foo.py. If you put all your imports at the top, you could have unexpected problems importing files that rely on information that hasn't been compiled yet. In this case, having a function local import can allow your code to hold off on importing the other module until its code has been fully compiled, and you call the relevant function.

However, it looks like your use-case is more about making it clear where foo() is coming from. In this case, I would far prefer one of two things:

First, rather than

from prerequisite import foo

import prerequisite directly, and later on refer to it as prerequisite.foo. The added verbosity pays itself back in spades through increased code transparency.

Alternatively, (or in conjunction with the above) if it's really such a long distance between your import and the place it's being used, it may be that your module is too big. The need for an import that nothing else uses might be an indication of a place where your code could stand to be refactored into a more manageably-sized chunk.


PEP8:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

It is not bad practice to have scopped imports. So that the import applies only to the function you used it in.

I think the code would be more readable though if the imports where grouped together at the top of the block or if you want it globally at the top of the file.


Well, I think it is a good practice to group all imports together at start of file since everyone knows where to look if want to know which libs are loaded

ReferenceURL : https://stackoverflow.com/questions/1188640/good-or-bad-practice-in-python-import-in-the-middle-of-a-file

반응형