Checking for required arguments when instantiating class.
Piet van Oostrum
piet at cs.uu.nl
Wed May 6 08:24:59 EDT 2009
>>>>> 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.
However this is very dirty trickery and should not be recommended. It
may also change in future versions and other implementations of Python.
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.
--
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org
More information about the Python-list
mailing list