builtin descriptor types

本文详细介绍了Python inspect模块中的getattr_static函数用法。该函数能在不触发动态查找的情况下获取对象属性,避免了通过描述符协议、__getattr__或__getattribute__进行查找。文章还讨论了该函数的一些限制情况及如何处理内置描述符类型的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

inspect. getattr_static ( objattrdefault=None )

Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__() or__getattribute__().

Note: this function may not be able to retrieve all attributes that getattr can fetch (like dynamically created attributes) and may find attributes that getattr can’t (like descriptors that raise AttributeError). It can also return descriptors objects instead of instance members.

If the instance __dict__ is shadowed by another member (for example a property) then this function will be unable to find instance members.

New in version 3.2.

getattr_static() does not resolve descriptors, for example slot descriptors or getset descriptors on objects implemented in C. The descriptor object is returned instead of the underlying attribute.

You can handle these with code like the following. Note that for arbitrary getset descriptors invoking these may trigger code execution:

# example code for resolving the builtin descriptor types
class _foo:
    __slots__ = ['foo']
slot_descriptor = type(_foo.foo)
getset_descriptor = type(type(open(__file__)).name)
wrapper_descriptor = type(str.__dict__['__add__'])
descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
result = getattr_static(some_object, 'foo')
if type(result) in descriptor_types:
    try:
        result = result.__get__()
    except AttributeError:
        # descriptors can raise AttributeError to
        # indicate there is no underlying value
        # in which case the descriptor itself will
        # have to do
        pass
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-35-b42d4f2a0683> in <module> 1 import pandas as pd 2 import numpy as np ----> 3 import tensorflow as tf 4 5 # 1. 加载CSV文件(针对指定路径) /usr/local/lib/python3.7/site-packages/tensorflow/__init__.py in <module> 22 23 # pylint: disable=g-bad-import-order ---> 24 from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import 25 26 from tensorflow._api.v1 import app /usr/local/lib/python3.7/site-packages/tensorflow/python/__init__.py in <module> 50 51 # Protocol buffers ---> 52 from tensorflow.core.framework.graph_pb2 import * 53 from tensorflow.core.framework.node_def_pb2 import * 54 from tensorflow.core.framework.summary_pb2 import * /usr/local/lib/python3.7/site-packages/tensorflow/core/framework/graph_pb2.py in <module> 13 14 ---> 15 from tensorflow.core.framework import node_def_pb2 as tensorflow_dot_core_dot_framework_dot_node__def__pb2 16 from tensorflow.core.framework import function_pb2 as tensorflow_dot_core_dot_framework_dot_function__pb2 17 from tensorflow.core.framework import versions_pb2 as tensorflow_dot_core_dot_framework_dot_versions__pb2 /usr/local/lib/python3.7/site-packages/tensorflow/core/framework/node_def_pb2.py in <module> 13 14 ---> 15 from tensorflow.core.framework import attr_value_pb2 as tensorflow_dot_core_dot_framework_dot_attr__value__pb2 16 17 /usr/local/lib/python3.7/site-packages/tensorflow/core/framework/attr_value_pb2.py in <module> 13 14 ---> 15 from tensorflow.core.framework import tensor_pb2 as tensorflow_dot_core_dot_framework_dot_tensor__pb2 16 from tensorflow.core.framework import tensor_shape_pb2 as tensorflow_dot_core_dot_framework_dot_tensor__shape__pb2 17 from tensorflow.core.framework import types_pb2 as tensorflow_dot_core_dot_framework_dot_types__pb2 /usr/local/lib/python3.7/site-packages/tensorflow/core/framework/tensor_pb2.py in <module> 13 14 ---> 15 from tensorflow.core.framework import resource_handle_pb2 as tensorflow_dot_core_dot_framework_dot_resource__handle__pb2 16 from tensorflow.core.framework import tensor_shape_pb2 as tensorflow_dot_core_dot_framework_dot_tensor__shape__pb2 17 from tensorflow.core.framework import types_pb2 as tensorflow_dot_core_dot_framework_dot_types__pb2 /usr/local/lib/python3.7/site-packages/tensorflow/core/framework/resource_handle_pb2.py in <module> 39 message_type=None, enum_type=None, containing_type=None, 40 is_extension=False, extension_scope=None, ---> 41 serialized_options=None, file=DESCRIPTOR), 42 _descriptor.FieldDescriptor( 43 name='container', full_name='tensorflow.ResourceHandleProto.container', index=1, /usr/local/lib/python3.7/site-packages/google/protobuf/descriptor.py in __new__(cls, name, full_name, index, number, type, cpp_type, label, default_value, message_type, enum_type, containing_type, is_extension, extension_scope, options, serialized_options, has_default_value, containing_oneof, json_name, file, create_key) 559 has_default_value=True, containing_oneof=None, json_name=None, 560 file=None, create_key=None): # pylint: disable=redefined-builtin --> 561 _message.Message._CheckCalledFromGeneratedFile() 562 if is_extension: 563 return _message.default_pool.FindExtensionByName(full_name) TypeError: Descriptors cannot not be created directly. If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0. If you cannot immediately regenerate your protos, some other possible workarounds are: 1. Downgrade the protobuf package to 3.20.x or lower. 2. Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and will be much slower). More information: https://developers.google.com/protocol-buffers/docs/news/2022-05-06#python-updates
最新发布
06-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值