alexmojaki / nameof

Python function to get the name of a variable or attribute, as in C#
MIT License
17 stars 2 forks source link

Problem with the dataclass attributes that have a field default value. #1

Closed AlirezaRoshanzamir closed 4 years ago

AlirezaRoshanzamir commented 4 years ago

Hello, First of all, thanks for the great useful library.

It seems that there is a problem with the dataclass attributes that have a field default value.

from dataclasses import dataclass, field
from typing import List

from nameof import nameof

@dataclass
class Foo:
    bar: List[int] = field(default_factory=lambda: [])

print(nameof(Foo.bar))

The above code raises:

AttributeError: type object 'Foo' has no attribute 'bar'

alexmojaki commented 4 years ago

Thanks, I'm glad you like it. You may also like https://github.com/pwwang/python-varname by @pwwang.

This has nothing to do with nameof. The attribute just doesn't exist, nothing nameof can help with, it doesn't even get called.

from dataclasses import dataclass, field
from typing import List

@dataclass
class Foo:
    bar: List[int] = field(default_factory=lambda: [])

print(Foo.bar)

This just seems to be how dataclasses work. default_factory=lambda: [] doesn't seem relevant.

You can still use the attribute on instances though:

print(nameof(Foo().bar))  # bar