5

Is it considered bad practice to have a class defined in a __init__.py file? I have a case that is 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 internally. Something like:

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 I'm thinking about looks like this:

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

And the __init__.py housed the "TaxCalculator" function.

Classes would reference the calculators ie:

from calculators import TaxCalculator

calculator = TaxCalculator().calculate(purchase_info)

Is that considered bad practice or not really Pythonic?

Brandon
  • 2,886
  • 3
  • 29
  • 44
  • 2
    I'm not sure this is the complete solution you are looking for, but the following Stackoverflow post has a good explanation of how it is typically used. http://stackoverflow.com/a/18979314/4194964 Talks about module level variables and how the __init__.py file should be thin to avoid violating the "explicit is better than implicit" philosophy – Brian Cain Oct 27 '15 at 22:31

1 Answers1

3

Typically the __init__.py file is used to initialize your package, like import stuff, add location to your path, defining versions or expose things with __all__, but often it's also empty. However I recommend you to give bigger classes/functions it's own files. It's much more maintainable.

tuxtimo
  • 2,730
  • 20
  • 29