CEP 520: None checks for extension type arguments in functions

Currently, Cython allows users to annotate typed Python function arguments with a "not None" syntax, as in

def func(MyExtType ext not None):
    return ext.some_c_method()

In the above example, a None check is required to prevent a crash when accessing the C-level method, as the MyExtType declaration allows None as a valid argument, in addition to all instances of MyExtType or a subtype.

This CEP proposes to

  1. replace (or accompany) the "not None" annotation that forbids None values with an "or None" annotation that allows them, for example:
    •     def func(MyExtType ext or None):
              if ext is None:
                  doSomethingElse()
              else:
                  ext.some_c_method()
  2. allow the 'not None' / 'or None' annotations also for builtin types, e.g.
    •     def func(list L or None):
              ...
  3. change the default behaviour of extension/builtin type arguments in functions to strictly test the type of the argument, i.e. to reject the value None and raise a TypeError for it.

  4. add a new directive allow_none_for_extension_args that allows to control the default behaviour.

Background

Proposal

The CEP proposes to replace the "not None" annotation by a reversed "or None" annotation, and to change the default behaviour from accepting None as a value for extension type arguments to a strict type test that rejects it.

Discussion

Pros:

Cons:

enhancements/argumentnonechecks (last edited 2010-04-16 11:36:09 by StefanBehnel)