Python 3.7에서는 Environment
리플렉션을 통해 OS 환경 변수를로드 할 수 있는 도우미 클래스를 작성했습니다 . 또한 파생 클래스에서 선언 된 형식 힌트를 기반으로 환경 변수를 네이티브 bool 또는 튜플로 변환합니다.
작동하지만 Visual Studio Code의 linter는이 문제 보고서를 제공합니다.
수업
'Environment'
에'__annotations__'
구성원 이 없습니다.
다음은 도우미 클래스입니다.
import os
from abc import ABC
class Environment(ABC):
@classmethod
def from_os(cls):
convert = {
bool: lambda d: d == "1",
(): lambda d: tuple(d.split(',')),
str: lambda d: d
}
values = [
convert[value](os.environ[key])
for key,value in cls.__annotations__.items()
]
return cls(*values)
다시 말하지만 코드는 실제로 작동합니다. Pylint를 행복하게하려면 어떻게해야합니까? 를 사용하지 않고 동일한 결과를 얻기 위해 속성 (및 속성 유형 힌트)을 반복 할 수있는 다른 방법이있을 수 있습니다 __annotations__
.
속임수를 사용하고 필 린트 억제 힌트를 추가하여 린터가 불평하는 것을 막을 수 있습니다.
for key,value in cls.__annotations__.items() # pylint: disable=no-member
...하지만 그것은 내가 찾고있는 해결책이 아닙니다.
도움이되는 경우 다음은 내 도우미 클래스를 사용하여 임의의 환경 변수 집합을 가져 오는 방법에 대한 예입니다.
from dataclasses import dataclass
@dataclass
class FWMonitoringEnv(Environment):
# The names of these attributes are used
# to find and load a corresponding environment variable.
# This happens when "FWMonitoringEnv.from_os()" is called.
preempt : bool
split_routes : bool
tag_key : str
vpc_summary_route : str
route_table_id : str
fw_trust_enis : ()
fw_mgmt_ips : ()
api_key_name : str
region : str
코드의 다른 곳에서는 간단히 다음을 실행합니다.
env = FWMonitoringEnv.from_os()
그 동안 수정하고 싶은 또 다른 코드 위생 문제가 있습니다. 내 Environment
클래스가 파생 클래스를 강제로 만들 수있는 방법 이 @dataclass
있습니까? 예를 들어, Python 3.7 유형 힌트로 수행 할 수 있습니까?
https://docs.python.org/3/library/inspect.html#inspect.signature 메서드를 사용 하여 모든 클래스 주석을 가져올 수 있습니다 .
예
pprint(inspect.signature(cls).parameters)
mappingproxy(OrderedDict([('preempt', <Parameter "preempt: bool">),
('split_routes', <Parameter "split_routes: bool">),
('tag_key', <Parameter "tag_key: str">),
('vpc_summary_route',
<Parameter "vpc_summary_route: str">),
('route_table_id', <Parameter "route_table_id: str">),
('fw_trust_enis', <Parameter "fw_trust_enis: ()">),
('fw_mgmt_ips', <Parameter "fw_mgmt_ips: ()">),
('api_key_name', <Parameter "api_key_name: str">),
('region', <Parameter "region: str">)]))
코드에 통합되면 다음과 같이 보입니다.
def from_os(cls):
convert = {
bool: lambda d: d == '1',
(): lambda d: tuple(d.split(',')),
str: lambda d: d
}
values = [
convert[val.annotation](os.environ[val.name])
for val in signature(cls).parameters.values()
]
return cls(*values)
나는 그것이 "진정한"방법을 얻는 더 나은 방법이라고 믿는다 :-)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다