Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inplace functions in Python

In Python there is a concept of inplace functions. For example shuffle is inplace in that it returns None.

How do I determine if a function will be inplace or not?

from random import shuffle

print(type(shuffle))

<class 'method'>

So I know it's a method from class random but is there a special variable that defines some functions as inplace?

like image 862
sayth Avatar asked Jul 28 '26 22:07

sayth


1 Answers

You can't have a-priory knowledge about the operation for a given function. You need to either look at the source and deduce this information, or, examine the doc-string for it and hope the developer documents this behavior.

For example, in list.sort:

help(list.sort)
Help on method_descriptor:

sort(...)
    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

For functions operating on certain types, their mutability generally lets you extract some knowledge about the operation. You can be certain, for example, that all functions operating on strings will eventually return a new one, meaning, they can't perform in-place operations. This is because you should be aware that strings in Python are immutable objects.

like image 141
Dimitris Fasarakis Hilliard Avatar answered Jul 31 '26 11:07

Dimitris Fasarakis Hilliard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!