Python __init__.py and classes

It is believed that bad practice has a class defined in the __init__.py file? I have a case similar to a tax calculator. I want to have a calculator class, and then a set of state-specific tax calculator classes that the calculator class references to the internal system. Sort of:

class TaxCalculator(): def __init__(self): self.ca_tax_calculator = CATaxCalculator() self.ny_tax_calculator = NYTaxCalculator() def get_tax_calculator_for_state(self, state): tax_calculator = None if state == "CA": tax_calculator = self.ca_tax_calculator else: tax_calculator = self.ny_tax_calculator return tax_calculator def calculate(self, purchase_info): return self.get_tax_calculator_for_state(purchase_info.state).calculate(purchase_info.amount) 

The directory structure that I think of is as follows:

 /calculators/__init__.py /calculators/ca.py /calculators/ny.py 

And in __init__.py the TaxCalculator function was posted.

Classes will refer to calculators, that is:

 from calculators import TaxCalculator calculator = TaxCalculator().calculate(purchase_info) 

Is this considered bad practice or not really Pythonic?

+5
source share
1 answer

Typically, the __init__.py file is used to initialize your package, such as importing, adding a location to your path, determining versions, or exposing things with __all__ , but it is often also empty. However, I recommend that you provide the larger classes / functions that it owns. It is much more convenient.

+3
source

Source: https://habr.com/ru/post/1234639/


All Articles