menu
techminis

A naukri.com initiative

google-web-stories
Home

>

Programming News

>

Glyph Lefk...
source image

PlanetPython

1w

read

394

img
dot

Glyph Lefkowitz: Stop Writing `__init__` Methods

  • Before the introduction of dataclasses in Python 3.7, the __init__ method was commonly used for object initialization.
  • Different alternatives to using __init__ method had their own drawbacks, such as making objects mutable or complex inheritance structures.
  • Having an empty __init__ method for simple object initialization was considered acceptable.
  • Problems arise when __init__ is used for complex object setups, like handling I/O operations.
  • The article suggests using dataclasses to define attributes and classmethods for object creation instead of __init__ for complex objects.
  • Using precise types and NewType to enforce object validity is recommended for better design.
  • Dataclasses with classmethods and NewType can provide more readable and maintainable code compared to manual __init__ methods.
  • The recommended best practices include using dataclasses, classmethods, and NewType for defining Python classes.
  • By adhering to these best practices, the code becomes more future-proof, testable, flexible, and easier to understand.
  • The article emphasizes that defining a custom __init__ method is considered an anti-pattern in modern Python development.

Read Full Article

like

23 Likes

For uninterrupted reading, download the app