Python에서 "global"문을 사용합니까?
저는 파이썬 글로벌 문 ( "Python scope" ) 에 대한 질문을 읽고 있었고 제가 파이썬 초보자 였을 때 ( 글로벌 을 많이 사용했을 때)이 문을 얼마나 자주 사용 했는지, 그리고 요즘 몇 년 후 전혀 사용하지 마십시오. 나는 심지어 그것을 "비 비단뱀 적"이라고 생각한다.
이 문장을 파이썬에서 사용합니까? 시간이 지남에 따라 사용법이 변경 되었습니까?
나는 다음과 같은 맥락에서 '글로벌'을 사용합니다.
_cached_result = None
def myComputationallyExpensiveFunction():
global _cached_result
if _cached_result:
return _cached_result
# ... figure out result
_cached_result = result
return result
나는 의미가 있고 무슨 일이 일어나고 있는지 기능의 독자에게 분명하기 때문에 '글로벌'을 사용합니다. 나는 또한이 패턴이 있다는 것을 알고 있는데, 이는 동등하지만 독자에게 더 많은인지 부하를줍니다.
def myComputationallyExpensiveFunction():
if myComputationallyExpensiveFunction.cache:
return myComputationallyExpensiveFunction.cache
# ... figure out result
myComputationallyExpensiveFunction.cache = result
return result
myComputationallyExpensiveFunction.cache = None
3 년 이상 Python을 전문적으로 사용하고 Python 취미로 5 년 이상 동안 프로덕션 코드에서이 명령문을 합법적으로 사용한 적이 없습니다. 변경해야하는 모든 상태는 클래스에 있거나 "전역"상태가있는 경우 전역 캐시와 같은 공유 구조에 있습니다.
함수가 전역 적으로 사용될 변수를 생성하거나 설정하는 상황에서 사용했습니다. 여기 예시들이 있습니다 :
discretes = 0
def use_discretes():
#this global statement is a message to the parser to refer
#to the globally defined identifier "discretes"
global discretes
if using_real_hardware():
discretes = 1
...
또는
file1.py:
def setup():
global DISP1, DISP2, DISP3
DISP1 = grab_handle('display_1')
DISP2 = grab_handle('display_2')
DISP3 = grab_handle('display_3')
...
file2.py:
import file1
file1.setup()
#file1.DISP1 DOES NOT EXIST until after setup() is called.
file1.DISP1.resolution = 1024, 768
In my view, as soon as you feel the need to use global variables in a python code, it's a great time to stop for a bit and work on refactoring of your code.
Putting the global
in the code and delaying the refactoring process might sound promising if your dead-line is close, but, believe me, you're not gonna go back to this and fix unless you really have to - like your code stopped working for some odd reason, you have to debug it, you encounter some of those global
variables and all they do is mess things up.
So, honestly, even it's allowed, I would as much as I can avoid using it. Even if it means a simple classes-build around your piece of code.
Objects are the prefered way of having non-local state, so global is rarely needed. I dont think the upcoming nonlocal modifier is going to be widely used either, I think its mostly there to make lispers stop complaining :-)
I use it for global options with command-line scripts and 'optparse':
my main() parses the arguments and passes those to whatever function does the work of the script... but writes the supplied options to a global 'opts' dictionary.
Shell script options often tweak 'leaf' behavior, and it's inconvenient (and unnecessary) to thread the 'opts' dictionary through every argument list.
I avoid it and we even have a pylint rule that forbids it in our production code. I actually believe it shouldn't even exist at all.
Rarely. I've yet to find a use for it at all.
It can be useful in threads for sharing state (with locking mechanisms around it).
However, I rarely if ever use it.
I've used it in quick & dirty, single-use scripts to automate some one-time task. Anything bigger than that, or that needs to be reused, and I'll find a more elegant way.
Once or twice. But it was always good starting point to refactor.
If I can avoid it, no. And, to my knowledge, there is always a way to avoid it. But I'm not stating that it's totally useless either
참고URL : https://stackoverflow.com/questions/146557/do-you-use-the-global-statement-in-python
'Development Tip' 카테고리의 다른 글
Kotlin의 정적 초기화 블록 (0) | 2020.11.24 |
---|---|
.NET Core- "dotnet new sln"을 사용하는 경우 (0) | 2020.11.24 |
멀티 스레딩 문제를 감지하고 디버깅하는 방법은 무엇입니까? (0) | 2020.11.24 |
C #에서 한 번만 속성을 설정하는 방법이 있습니까? (0) | 2020.11.24 |
유형 안전성과 관련하여 Haskell 유형 대 newtype (0) | 2020.11.24 |