Checking for required arguments when instantiating class.

Chris Rebert clp2 at rebertia.com
Wed May 6 14:36:48 CEST 2009


On Wed, May 6, 2009 at 5:24 AM, Piet van Oostrum <piet at cs.uu.nl> wrote:
>>>>>> Lacrima <Lacrima.Maxim at gmail.com> (L) wrote:
>
>>L> Hello!
>>L> For example I have two classes:
>
>>>>>> class First:
>>L>     def __init__(self, *args, **kwargs):
>>L>             pass
>
>>>>>> class Second:
>>L>     def __init__(self, somearg, *args, **kwargs):
>>L>             self.somearg = somearg
>
>>L> How can I test that First class takes 1 required argument and Second
>>L> class takes no required arguments?
>>L> So that I could instantiate them in a for loop.
>
>>>>>> a = [First, Second]
>>>>>> for cls in a:
>>L>     instance = cls()
>
>>L> Traceback (most recent call last):
>>L>   File "<pyshell#22>", line 2, in <module>
>>L>     instance = cls()
>>L> TypeError: __init__() takes at least 2 arguments (1 given)
>
>>L> Of course, I can do like this:
>>>>>> for cls in a:
>>L>     try:
>>L>             instance = cls()
>>L>     except TypeError:
>>L>             instance = cls('hello')
>
>>>>>> print instance.somearg
>>L> hello
>
>>L> But what if I have to instantiate any class with 3 or 4 required
>>L> arguments? How can I do it?
>
> cls.__init__.im_func.__code__.co_argcount
>
> This will include self, so it will be 1 in First and 2 in Second.

AFAICT, that would count non-required arguments too, which isn't
strictly what the OP requested.

> However this is very dirty trickery and should not be recommended. It
> may also change in future versions and other implementations of Python.

Very much agreed.

> I think it would be cleaner to put a class attribute in the classes that
> defines how they should be initialized (e.g. just the number of required
> arguments or more specific information) or have a special factory method
> for this use case.

Seconded. I'd recommend the latter personally, though it's impossible
to give a definitive answer without more context.

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list