Checking for required arguments when instantiating class.
Lie Ryan
lie.1296 at gmail.com
Wed May 6 06:51:47 EDT 2009
Lacrima wrote:
>>>>> 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?
>
>
> Sorry, I have made a mistake. Of course, Second class takes 1 required
> argument, not First.
Of course, it is possible to just try it one-by-one with a try block and
a while loop (as long as your class/function doesn't rely/change on some
global state (e.g. files, global variable, GUI, etc) while
initializing/called), but if you really need that, there is something
seriously wrong with the class/function design. You should check the
help and determine how many and what are all the arguments meant.
In case you're wondering, this is how it would look like:
>>> def f0():
... print
...
>>> def f1(a):
... print a
...
>>> def f2(a, b):
... print a, b
...
>>> def f2a(a, b, *args, **kargs):
... print a, b, args, kargs
...
>>> import itertools
>>> funclist = [f0, f1, f2, f2a]
>>> for f in funclist:
... for i in itertools.count():
... try:
... f(*range(i))
... except TypeError:
... pass
... else:
... print 'Function %s takes %s required arguments' %
(f.__name__, i)
... break
...
Function f0 takes 0 required arguments
0
Function f1 takes 1 required arguments
0 1
Function f2 takes 2 required arguments
0 1 () {}
Function f2a takes 2 required arguments
>>>
More information about the Python-list
mailing list