Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add __dataclass_fields__ and __attrs_attrs__ to dataclasses #8578

Merged
merged 18 commits into from
Aug 20, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions mypy/plugins/attrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,8 @@ def attr_class_maker_callback(ctx: 'mypy.plugin.ClassDefContext',
ctx.api.defer()
return

_add_attrs_magic_attribute(ctx)

# Save the attributes so that subclasses can reuse them.
ctx.cls.info.metadata['attrs'] = {
'attributes': [attr.serialize() for attr in attributes],
Expand Down Expand Up @@ -656,6 +658,20 @@ def _add_init(ctx: 'mypy.plugin.ClassDefContext', attributes: List[Attribute],
adder.add_method('__init__', args, NoneType())


def _add_attrs_magic_attribute(ctx: 'mypy.plugin.ClassDefContext') -> None:
attr_name = '__attrs_attrs__'
attr_type = ctx.api.named_type('__builtins__.tuple', [
ctx.api.named_type('attr.Attribute'),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ilevkivskyi ctx.api.named_type is for builtin types, but what i should use instead of it?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is not for builtin types, it is for types that are guaranteed to be present (i.e. loaded).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ilevkivskyi, and how to ensure that attr.Attribute is loaded? Or maybe need to use Any if it is not loaded?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They should be loaded, because the attr module must be analyzed if this plugin is called. The tests fail because they run with partial stubs, not the real ones, see for example https://github.com/python/mypy/blob/master/test-data/unit/lib-stub/attr.pyi, Attribute is not present there.

Also the latter is generic, so I would explicitly add a type argument here (even if it is Any).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They should be loaded, because the attr module must be analyzed if this plugin is called.

I have a problem with different styles of import of attr.

This example works fine:

import attr

@attr.s
class Foo:
    pass

class AttrsProtocol(Protocol):
    __attrs_attrs__: Tuple[attr.Attribute, ...]

def foo(x: AttrsProtocol) -> None:
    pass

foo(Foo())

But if I change import to:

from attr import attrs, Attribute

@attrs
class Foo:
    pass

I get exception:

  File "/Users/tkukushkin/Projects/mypy/mypy/plugins/attrs.py", line 664, in _add_attrs_magic_attribute
    ctx.api.named_type('attr.Attribute'),
  File "/Users/tkukushkin/Projects/mypy/mypy/semanal.py", line 4143, in named_type
    assert sym, "Internal error: attempted to construct unknown type"
AssertionError: Internal error: attempted to construct unknown type

Some tests fail because of this.

The tests fail because they run with partial stubs, not the real ones, see for example https://github.com/python/mypy/blob/master/test-data/unit/lib-stub/attr.pyi, Attribute is not present there.

Yes, I already added Attribute to stub, but not pushed yet.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, I just looked at the code of named_type() and it is horrible, it uses lookup_qualified() (which is just a normal symbol lookup following Python name resolution rules) so I wonder how it ever worked. You can try using named_type_or_none() instead, that one looks reasonable.

Another option is to actually fix named_type(), but it may be not the best task as a first contribution.

])
var = Var(name=attr_name, type=attr_type)
var.info = ctx.cls.info
ctx.cls.info.names[attr_name] = SymbolTableNode(
kind=MDEF,
node=var,
plugin_generated=True,
)


class MethodAdder:
"""Helper to add methods to a TypeInfo.

Expand Down
17 changes: 17 additions & 0 deletions mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,8 @@ def transform(self) -> None:

self.reset_init_only_vars(info, attributes)

self._add_dataclass_fields_magic_attribute()

info.metadata['dataclass'] = {
'attributes': [attr.serialize() for attr in attributes],
'frozen': decorator_arguments['frozen'],
Expand Down Expand Up @@ -361,6 +363,21 @@ def _freeze(self, attributes: List[DataclassAttribute]) -> None:
var._fullname = info.fullname + '.' + var.name
info.names[var.name] = SymbolTableNode(MDEF, var)

def _add_dataclass_fields_magic_attribute(self) -> None:
attr_name = '__dataclass_fields__'
dataclass_field_type = self._ctx.api.named_type('dataclasses.Field')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment here.

attr_type = self._ctx.api.named_type('__builtins__.dict', [
self._ctx.api.named_type('__builtins__.str'),
dataclass_field_type,
])
var = Var(name=attr_name, type=attr_type)
var.info = self._ctx.cls.info
self._ctx.cls.info.names[attr_name] = SymbolTableNode(
kind=MDEF,
node=var,
plugin_generated=True,
)


def dataclass_class_maker_callback(ctx: ClassDefContext) -> None:
"""Hooks into the class typechecking process to add support for dataclasses.
Expand Down