我正在尝试在 boto3 周围键入注释,但模块 'botocore.client' 没有属性'EC2'



我正在为boto3编写自己的包装器,用于快速启动函数。

我正在尝试键入注释boto3.session().client('ec2')返回的内容。

调试器说它是<class 'botocore.client.EC2'>,但如果我这样写,python会崩溃并出现运行时错误

ec2: botocore.client.EC2
AttributeError: module 'botocore.client' has no attribute 'EC2'

删除类型注释在运行时可以工作,但它使检查非常有限。

是否有一种合理的快速方法或hack来获得这种boto3情况下的打字工作?

我所说的代码如下:

class AWS_Client:
# debugger says it's <class 'botocore.client.EC2'>,
# but mypy says this class does not exist
ec2: botocore.client.EC2
asg: botocore.client.AutoScaling
region: str
instance_id: str
def __init__(self,
profile_name: Optional[str] = None,
instance_id: str = '',
region_name: str = '',
**kwargs) -> None:
global config
self.instance_id = instance_id or ec2_meta('instance-id').text
self.region = region_name or ec2_meta(
'placement/availability-zone').text[:-1]
boto3.set_stream_logger('botocore', level=logging.DEBUG)
self.session = call_partial(
boto3.Session,
region_name=self.region,
profile_name=profile_name,
**kwargs)
self.ec2 = self.session.client('ec2', region_name=self.region, **kwargs)
self.asg = self.session.client(
'autoscaling', region_name=self.region, **kwargs)
def get_tags(self) -> Dict[str, str]:
self.tags = self.ec2.describe_tags(Filters=[{
'Name': 'resource-id',
'Values': [self.instance_id]
}])['Tags']
return self.tags
aws = AWS_Client()
print(aws.get_tags())

试试mypy-boto3 mypy插件

你可以通过

安装
python -m pip install 'boto3-stubs[ec2]'
import boto3
from mypy_boto3_ec2 import EC2Client

def foo(ec2_client: EC2Client) -> None:
...

ec2_client = boto3.client("ec2")
foo(ec2_client)  # OK

最新更新