Python 2.7 Psycopg2 Reading Values From a Tuple List
Understand how to use NamedTuple and Dataclass in Python
Create a Python object beyond __init__
If I ask y'all to create a Python grade for the transaction record within 10 seconds, how would you lot exercise that? Probably creating a form with __init__ is what most people would do. In this commodity, I want to share 2 alternatives in Python to construct a class: Named Tuple and Dataclass. In the terminate, I will compare the operation of these iii options and give some suggestions on when to use which.
I will call the grade with _ _init__ every bit "regular" Python class in this commodity. Please let me know if in that location is an official name to information technology. If you want to deep swoop into Named Tuple and Dataclass, check out the reference links.
Each payment transaction has a sender, a receiver, a date and the amount. If I use the regular Python class, information technology might expect something like this:
It'southward very straightforward. Simply to be honest, it's a lot of code, at least a lot of lines. In a utilise example which I'1000 consuming real-fourth dimension transaction records from a source (e.g. Kafka), I don't want the flexibility to modify the tape. How would I accomplish that in a cleaner way?
Named Tuple
Named Tuple can be a smashing culling here to construct a class. Named Tuple is basically an extension of the Python built-in tuple information type. Python'southward tuple is a elementary information construction for grouping objects with different types. Its defining characteristic is being immutable.
An immutable object is an object whose state cannot exist modified later on it is created.
In Python, immutable types are int, float, bool, str, tuple and unicode.
Nonetheless, a downside of the congenital-in tuple type is that it puts a lot of responsibilities on a programmer. When yous access an attribute of the congenital-in tuple, you demand to know its index. Information technology will cause some defoliation if you are developing a library which will exist used by thousands of users.
Another possible way is to employ congenital-in dictionary, similar {"sender":"","receiver":"","date":"","amount":""} . But the trouble here is that y'all need to spell the fundamental names correctly. And it'due south not a grade at all.
We can avoid these problems using Named Tuple. Named Tuple allows united states to give names to the elements, so we can access the attributes by both aspect proper noun and its index.
There are really two types of Named Tuple in Python3.8. Ane is from collections package which has existed for a long fourth dimension, the other 1 is from typing package which has been introduced since Python3.vi.
collections.namedtuple
I volition offset with collections package. This bundle provides alternatives to Python's general born types like dict, list, set and tuple.
This is how to create a namedtuple class. WOW, simply one line of code!
The Transaction nosotros just created is essentially a class. It has attributes sender, receiver, date, amount and _fields, which allow us to access the aspect by both name and index.
Create an object
Creating a namedtuple object is as straightforward as creating the class. What I also like is the representation of the namedtuple object. You tin can also customize it in your regular Python class past overwriting __repr__ method.
Assigning attributes with a default value is besides possible.
⚠️ ️Attention!
In this example, I assign None to but one attribute as the default value. Which attribute is assigned? Think almost it.
None is assigned to attribute corporeality, which is the last attribute of the tuple.
What is happening here? I encourage you to retrieve for a infinitesimal before reading further.
Alright. Essentially, the creation of Named Tuple follows the aforementioned syntax as the regular Python class.
The magic is that when we create a class, non-default argument cannot follow default argument. In the regular Python form, we will immediately notice this error. This syntax dominion applies in Named Tuple as well, so the default value will be assigned starting from the concluding chemical element.
Back to the sub-topic: creating an object. It'south also possible to create an namedtuple object using _make() method. Just you need to remember the gild of the attributes.
Access the aspect
Accessing the attribute in namedtuple is also very straightforward. In fact, it'due south a tuple, nosotros can access the attribute like how nosotros practise it to the basic tuple. A namedtuple can exist converted to a lexicon with _asdict().
Assign the aspect
Wait? You lot just said tuple is an immutable data blazon, how could you lot assign the attribute in an immutable object?
That depends on the data type of the tuple attributes. If the attribute is immutable similar str, float, int, then we tin can't modify the land, such as ("1.0","xiaoxu","2019-01-01").
But if the attribute itself is mutable similar list, you are allowed to change the elements inside the listing without letting the tuple be enlightened of the modify.
In this case, the sender is a list which is a mutable object. Before modifying the aspect, I utilize Python built-in function id to cheque the memory address of the list.
Then I change the second element of the list to "gaga" and impress out the id of the same list. It turns out that the id is the same! Then, to namedtuple, the land hasn't been changed.
But if we create a new list with the same elements: "jojo" and "gaga" and attempt to assign information technology to the namedtuple, information technology won't work, considering they take dissimilar ids.
Inherit grade
Sometimes we want to inherit a class and extend the attributes. In namedtuple, you can add a new aspect using @holding. Information technology's just as easy as what yous see.
Assign field names to outcome in tuples returned by csv or db query
Another absurd feature I like most namedtuple is that information technology can map the csv record or db query consequence to a namedtuple object. It can reduce the corporeality of boilerplate code.
typing.NamedTuple
The second selection to create a namedtuple is using typing.NamedTuple. It'southward coming from typing package, so every attribute is bound to a type. In my stance, that's the only divergence between collections.namedtuple and typing.NamedTuple.
The format looks a flake like the regular Python grade but with typing. Make sure that you inherit typing.NamedTuple.
The class created from typing.NamedTuple has an actress field _field_types which shows the defined type of each aspect.
Sometimes, if y'all don't really desire to define a type to certain attributes, you can use type Whatsoever. A static type checker will treat every type as beingness compatiable with Any.
Create an object, Access the attribute & Assign the attribute
In terms of creating an object, accessing the attribute and assigning the attribute, typing.NamedTuple is the same as collections.tuple.
Dataclass
Dataclass is a new characteristic introduced since Python three.7. It is used every bit a decorator. What it does nether the hood is implementing __init__, __repr__ , etc for us.
Named Tuple behaves like a tuple, while dataclass behaves more than like a regular Python course. Why do I say that? Because past default, the attributes are all mutable and they can only be accessed by name, not by index.
Inherit grade
When inheriting a dataclass, the attribute of the bracket follows the parent class, so be careful with the default value. If a field in the parent class is assigned with a default value, so all the attributes in the subclass should take default values.
Immutable data class
I of the key features of Named Tuple is existence immutable. You can also gear up attributes immutable in dataclass via frozen=True.
In a frozen dataclass, FrozenInstanceError exception will be raised if you effort to alter the state.
Performance Comparison
Terminal simply not to the lowest degree, I desire to compare the functioning of regular Python class, collections.namedtuple, typing.NamedTuple and dataclass. The comparison includes:
- size of the object
- time to create the object
- time to retrieve the attribute
I take created v different classes. The concluding one is an optimised dataclass with a field __slot__. Slots are used to make classes faster and utilise less memory.
Compare the size of the object
The beginning step is to compare the size of each created object using sys.getsizeof.
Compare fourth dimension to create an object
And then I use Python built-in office timeit to compare the object creation fourth dimension.
Compare time to access an attribute
Result
Tuple based objects are in full general larger due to the fact that they contain both attribute names and indexes. dataclass with slots has the to the lowest degree object creation fourth dimension. The regular Python course seems to be good at accessing attributes.
barnettelawaseneved.blogspot.com
Source: https://towardsdatascience.com/understand-how-to-use-namedtuple-and-dataclass-in-python-e82e535c3691
0 Response to "Python 2.7 Psycopg2 Reading Values From a Tuple List"
Post a Comment