In general, is it reasonable to return None from a __new__
method if the user of the class knows that sometimes the constructor will evaluate to None?
The documentation doesn't imply it's illegal, and I don't see any immediate problems (since __init__
is not going to be called, None not being an instance of the custom class in question!). But I'm worried about
Specific example:
class MyNumber(int):
def __new__(cls, value): # value is a string (usually) parsed from a file
if value == 'N.A.':
return None
return int.__new__(cls, value)
If your function performs actions but doesn't have a clear and useful return value, then you can omit returning None because doing that would just be superfluous and confusing. You can also use a bare return without a return value just to make clear your intention of returning from the function.
Like you said, return None is (almost) never needed. But you should consider that the intention of your code is much clearer with an explicit return None . Remember: a piece of code also needs to be readable by human-beings, and being explicit usually helps. "Explicit is better than implicit."
If you want to return a null function in Python then use the None keyword in the returns statement. Example Python return null (None). To literally return 'nothing' use pass , which basically returns the value None if put in a function(Functions must return a value, so why not 'nothing').
__init__ doesn't return anything and should always return None .
Although it might seem natural to return None in some cases, it should be avoided because it can be error-prone. Let’s say you want to write a simple library function that divides two numbers. The function returns None when the denominator is 0. This makes sense as the result is undefined so sending None sounds natural.
00:19 There are basically three ways to cause a value of None to be returned from a function: if the function doesn’t have a return statement at all, if you have a return statement with no return value, or you can explicitly return None. 00:35 Let’s verify that all three of these cases actually do return a value of None.
The function returns None when the denominator is 0. This makes sense as the result is undefined so sending None sounds natural. However, the user of the function can incorrectly use it as shown below. When the numerator is 0, the function would return 0, which is expected but look at what happens in the if statement.
It's not illegal. If nothing weird is done with the result, it will work.
You should avoid this. The documentation doesn't exhaustively list the things you shouldn't do, but it says what __new__
should do: return an instance of the class.
If you don't want to return a new object in some cases, raise an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With