Is it possible to return None from __new__?

In general, is it wise to return None from the __new__ method if the class user knows that sometimes the constructor will evaluate None?

The documentation does not imply that it is illegal and I do not see any problems (since __init__ will not be called, None is not an instance of the corresponding class!). But i'm worried about

  • whether other unforeseen problems may arise.
  • Good programming practice for returning None constructors

Specific example:

 class MyNumber(int): def __new__(cls, value): # value is a string (usually) parsed from a file if value == 'NA': return None return int.__new__(cls, value) 
+6
python new-operator
source share
2 answers

This is not illegal. If nothing happens with the result, it will work.

+7
source share

You should avoid this. The documentation does not have an exhaustive list of things that you should not do, but it says what needs to be done __new__ : return an instance of the class.

If you do not want to return a new object in some cases, throw an exception.

+3
source share

All Articles