3

I've been looking around several posts on class initialization in python (e.g. Ref1, Ref2, Ref3) but I couldn't find if there's a clean way to require certain inputs. What would be the best approach to make a named argument required and throw a consistent exception if the argument is not included?

I would like to have a similar functionality to the require parameter of the add_argument() method in ArgumentParser.

Community
  • 1
  • 1
JAC
  • 591
  • 2
  • 6
  • 19

1 Answers1

5

Something like this should work:

class Foo(object):
    def __init__(self, required_arg=None):
        if required_arg is None:
            raise ValueError("Expected non-None value for required_arg")

If you want anything to be a valid value, as long as something is explicitly supplied, then you can do:

_Foo_default = object()
class Foo(object):
    def __init__(self, required_arg=_Foo_default):
        if required_arg is _Foo_default:
            raise ValueError("Expected a user-supplied value for required_arg")
Claudiu
  • 224,032
  • 165
  • 485
  • 680