Ritu Singh
Whether to use CustomType(TypedDict) or CustomType = NewType(...) in Python depends on your specific use case and the type of data you are working with. These two constructs serve different purposes and have different implications:
TypedDict:
TypedDict is used to define dictionaries with specific key-value type annotations. It is useful when you want to specify the structure of dictionaries, indicating the keys and their associated value types. This is particularly helpful when working with data that represents records or objects with well-defined fields. For example:
from typing import TypedDict
class Person(TypedDict):
name: str
age: int
Here, Person is a TypedDict that specifies that it should have a 'name' key with a string value and an 'age' key with an integer value.
Use TypedDict when you want to enforce a specific structure for dictionaries, especially when working with type checking tools like mypy.
NewType:
NewType is used to create distinct types based on an existing type. It is helpful for improving code readability and maintainability by creating more specific types for values that have the same underlying type. For example:
from typing import NewType
UserId = NewType('UserId', int)
Here, UserId is a new type that is essentially an int, but it provides a clear distinction between regular integers and user IDs, which can make the code more self-explanatory.
Use NewType when you want to create more specific types without the need to create new classes or structures.
In summary:
Use TypedDict when you want to specify the structure of dictionaries, especially when dealing with data records or objects with known fields.
Use NewType when you want to create more specific types based on existing types to improve code readability and maintainability, especially for values that share the same underlying type but have different meanings in your code.
Ultimately, the choice between TypedDict and NewType depends on the specific requirements of your project and how you intend to use these types in your code.
Suggested blogs:
>How to save python yaml and load a nested class?
>What makes Python 'flow' with HTML nicely as compared to PHP?