Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create type object in python similar to type object in typescript

How can i create these data types in Python ?
These types were defined in typescript and i want to recreate it in python. How can i do it in python easily and correctly?

   export type Category =
    'painting'
    | 'work on paper'
    | 'print'
    | 'ceramic'
    | 'installation'
    | 'sculpture'
    | 'textile'
    | 'photograph'
    | 'other'

export type NumberedCategory = `${Category}-${number}`

export type Lexicon = { term: string, weight: number }

export type Score = { name: string, score: number, contributors: string[] }

Thank you!

like image 719
inkarar Avatar asked Nov 15 '25 17:11

inkarar


1 Answers

I am not super familiar with typescript, but in Python you can create types by creating classes.

I created a Score type just like the one in your example inside an ipython REPL as an example.

In [1]: class Score:
   ...:     def __init__(self, name: str, score: int, contributors: list):
   ...:         self.name = name
   ...:         self.score = score
   ...:         self.contributors = contributors

In [2]: isinstance(Score, type)
Out[2]: True

In [3]: score = Score("ten", 10, ["contributor1", "contributor2"])

In [4]: isinstance(score, Score)
Out[4]: True

In [5]: type(score)
Out[5]: __main__.Score

In [6]: type(Score)
Out[6]: type
like image 74
Alexander Avatar answered Nov 17 '25 07:11

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!