Blue Monday Blue Monday - 1 year ago 62
Python Question

No return statement but still returning None

My function is just to modify a list.However, I don't want it to return anything not even 'None' and yet it returns 'None'. Is there a way to fix this?

Answer Source

TL;DR: No, there is not a meaningful way around default return of None in Python.

In Python, returning an implied None is the closest you can do to "return nothing". This is different to e.g. C where a void function declaration would prevent assignment to a variable. This behaviour is part of the Python language for consistency, because

x = MyFunc()

must define and store some value in x. Similarly, uses such as

OtherFunc( 1, 2, MyFunc() )


[ 1, 2, 3, MyFunc() ]


MyFunc() * 3

All need to have some behaviour. With an implied return value of None, these issues are solved in a particular way in Python.

It doesn't have to be this way - in principle if someone were to re-design this part of Python there could be a few different self-consistent approaches - for instance Python could have some special value that could only be returned from function calls and if it was found to be inside any other expression that could raise an error.

However, Python returns implicit None. Changing this would affect any code/libraries that rely on the behaviour in a global way, or add awkward context-parsing requirements to the language because the feature necessarily would need to work both inside function definitions and where those functions were used.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download