Checking for required arguments when instantiating class.

Chris Rebert clp2 at rebertia.com
Wed May 6 12:28:53 CEST 2009


On Wed, May 6, 2009 at 3:08 AM, Lacrima <Lacrima.Maxim at gmail.com> wrote:
> Hello!
>
> For example I have two classes:
>
>>>> class First:
>        def __init__(self, *args, **kwargs):
>                pass
>
>>>> class Second:
>        def __init__(self, somearg, *args, **kwargs):
>                self.somearg = somearg
>
> How can I test that First class takes 1 required argument and Second
> class takes no required arguments?

import inspect
args, varargs, varkw, defaults = inspect.getargspec(klass)
num_args_reqd = len(args) - (0 if defaults is None else len(defaults))

However, it sounds like a code smell that you're instanciating unknown
classes that don't share a common constructor signature.

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



More information about the Python-list mailing list