12

Python 3.7 引入了dataclasses包含@dataclass装饰器的模块。这个装饰器可以生成类函数。如何打印这些生成的函数?

4

2 回答 2

4

我自己也问过同样的问题。Dataclasses部分项目应该有详细的选项,但不是。

找到这个视频,很有帮助。根据视频 dataclasses.py 是一个代码生成器。所以这应该是我们如何获取代码的第一个想法。


我试过这段代码:

from dataclasses import dataclass
import inspect
import os
from uncompyle6 import PYTHON_VERSION, deparse_code2str

@dataclass
class C:
    name: str
    value: int = 34

inspect.getmembers(C) #('__init__', <function __init__(self, name: str, value: int = 34) -> None>)

co= C.__init__.__code__ # let's find out code for the __init__ method from code object

code = deparse_code2str(
                code=co,
                version=PYTHON_VERSION,
                out=open(os.devnull, "w"))
print(code)

将打印

self.name = name
self.value = value

该代码实际上使用检查器来理解类,然后使用 Python 反编译器对方法进行反编译。

以下是发现的方法:

def __eq__(self, other):
    if other.__class__ is self.__class__:
        return (self.name, self.value) == (
            other.name,
            other.value,
        )
    else:
        return NotImplemented

def __init__(self, name: str, value: int = 34) -> None:
    self.name = name
    self.value = value

def __repr__(self):
    key = (id(self), _thread.get_ident())
    if key in repr_running:
        return "..."
    else:
        repr_running.add(key)
        try:
            result = user_function(self)
        finally:
            repr_running.discard(key)

        return result

实际上有一个项目正在做@dataclass 发现。我安装了它,它工作。

from dataclasses import dataclass
import inspect
import os
import dis
from DataclassInspector.inspector import Inspector

@dataclass
class C:
    name: str
    value: int = 34

inspected = Inspector(C)
print(inspected._generate_code())

提供这样的输出:

from dataclasses import Field, _MISSING_TYPE, _DataclassParams
class C:
    __dataclass_fields__ = {'name': "Field(name='name', type=str, default=_MISSING_TYPE, default_factory=_MISSING_TYPE, init=True, repr=True, hash=None, compare=True, metadata={}, _field_type=_FIELD)", 'value': "Field(name='value', type=int, default=34, default_factory=_MISSING_TYPE, init=True, repr=True, hash=None, compare=True, metadata={}, _field_type=_FIELD)"}
    __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)
    name: str
    value: int = 34

    def __eq__(self, other):
        if other.__class__ is self.__class__:
            return (self.name, self.value) == (other.name, other.value)
        else:
            return NotImplemented


    __hash__ = None

    def __init__(self, name: str, value: int = 34) -> None:
        self.name = name
        self.value = value



    def __repr__(self):
        key = (
         id(self), _thread.get_ident())
        if key in repr_running:
            return '...'
        else:
            repr_running.add(key)
            try:
                result = user_function(self)
            finally:
                repr_running.discard(key)

            return result
于 2019-06-04T23:00:40.070 回答
1

在检查了数据类实现之后,这些方法似乎是由dataclasses._create_fn. 为了获得原始生成的代码,我将函数模拟为:

import dataclasses

_original_create_fn = dataclasses._create_fn

def _new_create_fn(name, args, body, **kwargs):
    args_str = ', '.join(args)
    body_str = '\n'.join('  ' + l for l in body)
    print(f'def {name}({args_str}):\n{body_str}\n')
    return _original_create_fn(name, args, body, **kwargs)

dataclasses._create_fn = _new_create_fn


# After the dataclasses as been mocked, creating new dataclass
# will display their source code
@dataclasses.dataclass
class A:
    x: int
    y: int

显示如下:

def __init__(self, x:_type_x, y:_type_y):
  self.x=x
  self.y=y

def __repr__(self):
  return self.__class__.__qualname__ + f"(x={self.x!r}, y={self.y!r})"

def __eq__(self, other):
  if other.__class__ is self.__class__:
   return (self.x,self.y,)==(other.x,other.y,)
  return NotImplemented
于 2021-04-23T14:57:01.310 回答