Data Classes in Python | Set 6 (interconversion to and from other datatypes)

Prerequisite: Data Classes in Python | Set 5

In the last post of DataClass series, we will discuss how to get values of a DataClass object into a dictionary or tuple pairs and how to create a DataClass in a different way – from values, instead of defining it directly.

asdict() function –



dataclasses.asdict(instance, *, dict_factory=dict)

One can simply obtain an attribute to value pair mappings in form of a dictionary by using this function, passing the DataClass object to the instance parameter of the function.

astuple() function –

dataclasses.astuple(instance, *, tuple_factory=tuple)

Similar to asdict, one can simply obtain ordered values of dataclass attributes in the form of a tuple using this function by passing the DataClass object to the instance parameter of the function.

filter_none

edit
close

play_arrow

link
brightness_4
code

from dataclasses import dataclass, field, 
from dataclasses import asdict, astuple
  
@dataclass
class GfgArticle:
  
    title : str
    language: str
    author: str
    upvotes: int = field(default = 0)
  
  
dClassObj = GfgArticle("DataClass",
                       "Python3",
                       "vibhu4agarwal")
  
dictArticle = asdict(dClassObj)
tupleArticle = astuple(dClassObj)
  
print(dictArticle)
print(tupleArticle)

chevron_right


Output:

{‘title’: ‘DataClass’, ‘language’: ‘Python3’, ‘author’: ‘vibhu4agarwal’, ‘upvotes’: 0}
(‘DataClass’, ‘Python3’, ‘vibhu4agarwal’, 0)

make_dataclass() function –

dataclasses.make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)

This function helps you to create DataClass (not an object of DataClass object) by passing its name and various attributes in form of string. This comes in handy when you want to dynamically create a DataClass whose attributes names might depend on certain values, and you can then pass their names through str variables.
In the above function, if just name is supplied, typing.Any is used for type.
The values of init, repr, eq, order, unsafe_hash, and frozen have the same meaning as they do in dataclass().

filter_none

edit
close

play_arrow

link
brightness_4
code

from dataclasses import make_dataclass, field
  
GfgArticle = make_dataclass(
    'GfgArticle',
    [
        ('title', str),
        ('language', str),
        ('author', str),
        ('upvotes', int, field(default = 0))
    ]
)
  
dClassObj = GfgArticle("DataClass",
                       "Python3",
                       "vibhu4agarwal")
print(dClassObj)

chevron_right


Output:

GfgArticle(title=’DataClass’, language=’Python3′, author=’vibhu4agarwal’, upvotes=0)

As this is the last post, here’s a bonus function.

is_dataclass() function –

dataclasses.is_dataclass(class_or_instance)

This function returns True if its parameter is a dataclass or a DataClass object, otherwise returns False.

filter_none

edit
close

play_arrow

link
brightness_4
code

from dataclasses import is_dataclass
  
print(is_dataclass(dictArticle))
print(is_dataclass(tupleArticle))
  
print(is_dataclass(dClassObj))
print(is_dataclass(GfgArticle))
  
print(is_dataclass(dClassObj) and not isinstance(dClassObj, type))
print(is_dataclass(GfgArticle) and not isinstance(GfgArticle, type))

chevron_right


Output:

False
False
True
True
True
False


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.