20200728 python 관련 사소한 팁

2020. 7. 28. 23:11개발/Python

1.@property

python을 해본 사람은 누구나 알듯이 public, private같은 접근 제어자가 없다. 그래서 다른 언어에서는 private으로 쓸 것을 변수 앞에 밑줄 두개(__)를 써서, protected는 밑줄 하나(_)를 써서 표현한다. 보통 다른 언어에서 이들을 가져오고 싶거나 세팅하고 싶을 때 get, set 함수를 쓴다. python에서 이를 똑같이 하면 다음과 같다.

class Everything:
	def __init__(self):
    	self.__name = "any name"
    def get_name(self):
    	return self.__name
	def set_name(self, new_name:str):
    	self.__name = new_name

하지만 이런 식으로 하면 상당히 복잡해진다. property와 setter을 활용하자.

 

class EveryThing:
	def __init__(self):
    	self.__name = "anything"

	@property
    def name(self):
    	return self.__name
        
	@name.setter
    def name(self, name:str):
    	self.__name = name

참고: https://medium.com/@hckcksrl/python-property-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0-89eb0f0e2e56

2.context manager

contextlib 패키지 안에 있는 contextmanager에 관한 글이다. 이를 활용하면 해당 함수 내에서 리소스를 점유하고 풀 대상이 필요할 때 리소스를 release를 일일이 하지 않고 with문을 활용하여 간편하게 제어 가능하다. 활용은 다음과 같다. 

from contextlib import contextmanager

@contextmanager
def some_function():
	resource = acquire_resource(*args, **kwargs)
    try:
    	yield resource
	finally:
    	release(resource)
        
        
with some_function() as resource:
	blabla

이를 어디다 잘 활용할 수 있을까? db connection같은 것에 resource를 할당하고 release하면 찰떡궁합이 아닐 수 없다. contextlib에서 asynccontextmanager를 활용하여 이와 같은 함수를 async하게 처리할 수도 있다하니 필요하면 쓰는 것도 좋겠다.