Data Classes in Python | Set 6 (interconversion to and from other datatypes)
Last Updated :
15 Apr, 2019
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.
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)
|
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().
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)
|
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
.
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 ))
|
Output:
False
False
True
True
True
False
Similar Reads
Data Classes in Python | Set 3 (dataclass fields)
Prerequisite: Data Classes in Python Set 1 | Set 2 In this post we will discuss how to modify certain properties of the attributes of DataClass object, without explicitly writing code for it using field function. field() function - dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=
4 min read
Data Classes in Python | An Introduction
dataclass module is introduced in Python 3.7 as a utility tool to make structured classes specially for storing data. These classes hold certain properties and functions to deal specifically with the data and its representation.DataClasses in widely used Python3.6 Although the module was introduced
3 min read
The Ultimate Guide to Data Classes in Python 3.7
This article discusses data classes in Python 3.7 and provides an introductory guide for data classes in Python 3.7 and above. Data Class is a new concept introduced in Python 3.7 version. You can use data classes not only as a knowledge container but also to write boiler-plate code for you and simp
4 min read
Change Data Type for one or more columns in Pandas Dataframe
When working with data in Pandas working with right data types for your columns is important for accurate analysis and efficient processing. Pandas offers several simple ways to change or convert the data types of columns in a DataFrame. In this article, we'll look at different methods to help you e
3 min read
How to convert categorical string data into numeric in Python?
The datasets have both numerical and categorical features. Categorical features refer to string data types and can be easily understood by human beings. However, machines cannot interpret the categorical data directly. Therefore, the categorical data must be converted into numerical data for further
4 min read
SQLite Datatypes and its Corresponding Python Types
SQLite is a C-language-based library that provides a portable and serverless SQL database engine. It has a file-based architecture; hence it reads and writes to a disk. Since SQLite is a zero-configuration database, no installation or setup is needed before its usage. Starting from Python 2.5.x, SQL
3 min read
Python bit functions on int (bit_length, to_bytes and from_bytes)
The int type implements the numbers.Integral abstract base class. 1. int.bit_length() Returns the number of bits required to represent an integer in binary, excluding the sign and leading zeros. Code to demonstrate num = 7 print(num.bit_length()) num = -7 print(num.bit_length()) Output: 3 3 2. int.t
1 min read
How To Convert Sklearn Dataset To Pandas Dataframe In Python
In this article, we look at how to convert sklearn dataset to a pandas dataframe in Python. Sklearn and pandas are python libraries that are used widely for data science and machine learning operations. Pandas is majorly focused on data processing, manipulation, cleaning, and visualization whereas s
3 min read
How to read a numerical data or file in Python with numpy?
Prerequisites: Numpy NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. This article depicts how numeric data can be read from a file using Numpy. Numerical data can be present in different format
4 min read
Python set operations (union, intersection, difference and symmetric difference)
Sets are a fundamental data structure in Python that store unique elements. Python provides built-in operations for performing set operations such as union, intersection, difference and symmetric difference. In this article, we understand these operations one by one. Union of setsThe union of two se
3 min read