Most pythonic ways to handle parameter combinations to instantiate a class?

Let's say I have a Foo class:

class Foo(object):
    @staticmethod
    def get_a(b, c):
        if not b or not c:
            raise ValueError("Invalid params!")
        return b + c

    def __init__(self, a=None, b=None, c=None):
        if not a:
            a = Foo.get_a(b, c)
        self.a = a

      

The user can use the class with a

or both b

and c

. If a, then b

and are c

ignored.

Which is better: a bug where all three parameters provided (make sure the programmer is aware of which one is used) or put them in documents b

and c

will be ignored if it is provided?

On the one hand, the error is more explicit, which is pythonic (Explicit is better than implicit). On the other hand, accepting any kind of work is more practical (although practicality trumps cleanliness).

+3


source to share


1 answer


I would assign a separate classmethod

factory to the class :

class Foo(object):
    def __init__(self, a):
        self.a = a

    @classmethod
    def from_b_and_c(cls, b, c):
        return cls(b + c)

      

This is a real explicit option; you either instantiate Foo(a)

or use Foo.from_b_and_c(b, c)

to instantiate with very different arguments. This immediately documents how the parameters are separate; either you instantiate with only a

, or instantiate both from b

and c

together.



This is a common pattern; if you have multiple ways to instantiate, provide additional factory methods as class methods.

For example, you can create a class datetime.date()

with:

+6


source







All Articles