sayth
sayth

Reputation: 7048

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?

Upvotes: 3

Views: 1034

Answers (2)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160467

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.

Upvotes: 5

Munir Hossain
Munir Hossain

Reputation: 383

I don't think there is special variable that defines some function as in-place but a standard function should have a doc string that says that it is in-place and does not return any value. For example:

>>> print(shuffle.__doc__)

Shuffle list x in place, and return None.

    `Optional argument random is a 0-argument function returning a
    random float in [0.0, 1.0); if it is the default None, the
    standard random.random will be used.`

Upvotes: 2

Related Questions