-2

I would like to create a dictionary, but use static typing so I am certain the value assigned is the correct type, like you can do with variables or parameters. Is this possible?

petezurich
  • 9,280
  • 9
  • 43
  • 57
Steve Scott
  • 1,441
  • 3
  • 20
  • 30
  • 1
    Please update your question with the code you have tried. – quamrana Aug 15 '22 at 19:38
  • You might want to look into tools like Pydantic (not sure it'll solve your problem but it's a good bet) or use OOP. Also, I suspect this is a bad question for SO. – eccentricOrange Aug 15 '22 at 19:39
  • 2
    https://docs.python.org/3/library/typing.html#typing.TypedDict? Or something else - are you looking for _runtime_ type checking, or ...? Strong typing is quite different to static typing, for example. – jonrsharpe Aug 15 '22 at 19:40
  • 2
    @quamrana This isn't a debugging question, and code has never been a requirement for a good question. – SuperStormer Aug 15 '22 at 19:48
  • 1
    Anyways, this is either a dupe of https://stackoverflow.com/questions/44225788/python-3-dictionary-with-known-keys-typing (static type checker) or https://stackoverflow.com/questions/69555006/how-to-type-hint-type-check-a-dictionary-at-runtime-for-an-arbitrary-number (runtime type checker), depending on which one OP wants. – SuperStormer Aug 15 '22 at 19:51
  • There are several type validators in python, for simple use I would recommend `TypedDict` as several comments pointed out. You can use Pydantic in bigger projects, for example building an API with `FastAPI`. There are other validators for other structures, but that's beyond the scope of your question. – Mohamed Yasser Aug 15 '22 at 19:53
  • 3
    `TypedDict` is the way to go if you want it to be a dict, but in most situations where I'd previously have used a `TypedDict` I'll now use a `dataclass` instead. – Samwise Aug 15 '22 at 19:58

1 Answers1

1

You can import TypedDict from typing and use it! See this sample:

from typing import TypedDict
class Movie(TypedDict):
  name: str
  rank: int

and now, python will accept something like this:

movie: Movie = { ‘name’: ‘God Father’, ‘rank’: 1 }

but if you give name, a value of int type, or give rank a value of double type for example, python type checking will give you error!

you can also refer to this link for more info.