4 ms·
You're 100% right, the new type annotations are really nice to. You can still be really pythonic and leverage some cool reflection capabilities with types. An
by maldev 4y ago
You're 100% right, the new type annotations are really nice to. You can still be really pythonic and leverage some cool reflection capabilities with types. And on your point of forcing people to use types. I can't imagine many situations where you don't have a type in mind and can't use a higher order function to solve the problem. Which python does internally with __add__ __str__ and all the other functions included with classes.
As an example of stuff you can do with types. I was trying to teach a buddy how to program from a non CS background and I explored it a bit to make it as modular as possible so he could literally just change the structure and types and the code would all work for him. And it's really easy using some reflection
For example, to mimic a struct, you can use.
@dataclass
class CSVStruct:
x: int = 0
y: int = 0
foo: int = 0
bar: int = 0
Then you can typecast dynamically and generate random data(assuming you can go from int -> datatype) to fille in the data.
arg_list = []
# Generating argument list dynamically
for field in dataclasses.fields(self.CSVStruct):
arg_list.append(field.type(randint(0, 100)))
Or to get all the names of a struct (In this case to print out any structure with headers into a CSV file. Can also be done with their values)
# Getting column names
row_names = {field.name: field.type for field in dataclasses.fields(self.CSVStruct)}