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

Type annotation required? #2

Closed
ericvsmith opened this issue May 21, 2017 · 9 comments
Closed

Type annotation required? #2

ericvsmith opened this issue May 21, 2017 · 9 comments

Comments

@ericvsmith
Copy link
Owner

ericvsmith commented May 21, 2017

For:

@dataclass
class C:
    x: int = 0
    y = 0

Is y a field? What are the params to init()? Just x? Or x and y?

dataclass doesn't need to look at annotations, so there's no technical reason they'd be required.

My personal preference is to require them. That is, drive field discovery from __annotations__, not something like [name for name in C.__dict__ if not name.startswith('_')]

@gvanrossum
Copy link

Agreed. y is not a field.

@ericvsmith
Copy link
Owner Author

Thanks, Guido.

@tommikaikkonen
Copy link

This requirement tripped me up. Consider the following code:

from dataclasses import dataclass, field

@dataclass
class Wrapper:
    value = field()

I assumed I could use it like:

instance = Wrapper(1)

But because the value = field() declaration does not have a type annotation, Wrapper(1) raises a TypeError.

TypeError: __init__() takes 1 positional argument but 2 were given

To get it to work, I have to import typing and use Any:

from typing import Any

@dataclass
class Wrapper:
    value: Any = field()

which adds unneeded verbosity to unannotated code. It would be nice if unannotated attributes on a dataclass decorated declaration that are instances of dataclasses.Field would be treated as fields on the data class.

@gvanrossum
Copy link

gvanrossum commented Dec 26, 2017 via email

@ilevkivskyi
Copy link
Contributor

@gvanrossum I however think it is better to give a clear error in this case, not just silently ignore the fields that are not in __annotations__.

@gvanrossum
Copy link

gvanrossum commented Dec 26, 2017 via email

@ericvsmith
Copy link
Owner Author

https://bugs.python.org/issue32428

@gpshead
Copy link

gpshead commented Dec 27, 2017

I was going to suggest object earlier in the python-dev thread but wasn't sure how object differs from Any in meaning. If you're good with object, so am I.

That'd be less complicated than my suggestion of a Data = "typing.any" alias in the dataclasses module.

@gvanrossum
Copy link

gvanrossum commented Dec 30, 2017 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants