How to assemble a set of different data types into a named structure in python?

Asked

Viewed 63 times

2

Good afternoon, I had a question about how to gather a set of different types of data in a structure named in Python. I’m in the process of migrating from Delphi to the Python language. But I want to do something like command 'record' delphi.

1 answer

4


For Python 3.7+ you can use the dataclasses.dataclass:

from dataclasses import dataclass

@dataclass
class TModo:
    descricao: str
    valor_i: str
    valor_f: str
    versao: int

Due to the presence of the decorator, some methods will be built for you in the class, including the initializer method. So to create a new instance of TModo just do:

tmodo = TModo('Descrição', 'valor i', 'valor f', 1)

Remember that Python has dynamic typing and the types above are only type annotations, that is, they will not change in any way when executing the code. So even if you specify which version is int, I can assign you a string no problems - but this is a feature of the language, not the implementation.

Another alternative is to use the named tuples. For Python 3.5+ you can use the setting from typing.NamedTuple:

from typing import NamedTuple

class TModo(NamedTuple):
    descricao: str
    valor_i: str
    valor_f: str
    versao: int

Or for earlier versions you can use collections.namedtuple:

from collections import namedtuple

TModo = namedtuple('TModo', ['descricao', 'valor_i', 'valor_f', 'versao'])

To know the difference between them:

  • Thanks Anderson, it served me very well! Obg

Browser other questions tagged

You are not signed in. Login or sign up in order to post.