3

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?

1
  • 2
    I think you have to read the docstring. Commented Oct 19, 2016 at 8:48

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The string because its a compound data type? Because if you use list with a string then for example shuffle would act on it as inplace.
@sayth operations (function) on strings always return a new string because strings are immutable. Operations on lists (regardless of content) can be in-place since lists can be mutated.
2

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.`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.