diff --git a/Doc/library/functools.rst b/Doc/library/functools.rst --- a/Doc/library/functools.rst +++ b/Doc/library/functools.rst @@ -445,6 +445,12 @@ would have been ``'wrapper'``, and the docstring of the original :func:`example` would have been lost. +.. function:: identity(obj) + + Mathematical identity function which returns the argument unchanged. + If you have to ask when you would use this, you don't need to use this. + + .. versionadded:: 3.6 .. _partial-objects: diff --git a/Lib/functools.py b/Lib/functools.py --- a/Lib/functools.py +++ b/Lib/functools.py @@ -85,6 +85,11 @@ assigned=assigned, updated=updated) +def identity(obj): + """Mathematical identity function. Returns its argument unchanged.""" + return obj + + ################################################################################ ### total_ordering class decorator ################################################################################ diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py --- a/Lib/test/test_functools.py +++ b/Lib/test/test_functools.py @@ -1959,6 +1959,12 @@ self.assertEqual(len(td), 0) functools.WeakKeyDictionary = _orig_wkd +class TestIdentity(unittest.TestCase): + def test_identity(self): + identity = functools.identity + for obj in ["a b c", 99.99, [], {}, object(), (1,), [3, 4, 5]]: + self.assertIs(obj, identity(obj)) + if __name__ == '__main__': unittest.main()