NOOBAF
NOOBAF

Reputation: 187

Python Dataclass - getting metadata from attribute name

I have a Dataclass that looks like this:

@dataclass
class Example:
    smtng: int = field(init=True, metadata={'int_name':"Thing",'ext_name':"it"})
    smtng_else: str = field(init=True, metadata={'int_name':"other",'ext_name':"that"})

as you can see the metadata dict has external and internal name fields I would like to access these through functions E.g. get_ext_name(attribute_name) -> which would return an attribute's name under the metadata dict "ext_name"

is there a sleek way to to this?

Thanks

Upvotes: 3

Views: 7348

Answers (1)

NOOBAF
NOOBAF

Reputation: 187

So I found this way to do it thanks to vibhu4agarwal on GeeksForGeeks.

Adding this method to the class works:

def ext_name(self, attribute_name):
    return self.__dataclass_fields__[attribute_name].metadata['ext_name'])

if there's a better workaround I'd love to see it

here's a link to the article: https://www.geeksforgeeks.org/data-classes-in-python-set-3-dataclass-fields/

Upvotes: 5

Related Questions