Is There a Builtin Identity Function in Python

Is there a builtin identity function in python?

Doing some more research, there is none, a feature was asked in issue 1673203 And from Raymond Hettinger said there won't be:

Better to let people write their own trivial pass-throughs
and think about the signature and time costs.

So a better way to do it is actually (a lambda avoids naming the function):

_ = lambda *args: args
  • advantage: takes any number of parameters
  • disadvantage: the result is a boxed version of the parameters

OR

_ = lambda x: x
  • advantage: doesn't change the type of the parameter
  • disadvantage: takes exactly 1 positional parameter

Python identity function in a command-line enhancer program

No, Python does not have an identity function, and is unlikely to get one.

What would one look like? Easier, perhaps, to answer what it should do:

something = ...
something is identity(something)

in other words, you should get back exactly what you put in, and, ideally, you should be able to put anything in.

A tempting, but inadequate, solution:

wrong_id1 = lambda x: x

The problem with this version is that we can only pass single items in, so this works:

>>> wrong_id1('a thing')
'a thing'

but this does not:

>>> wrong_id1('a thing', 'and another thing')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 argument (2 given)

The next tempting solution might be:

wrong_id2 = lambda *x: x

and this does work for multiple inputs:

>>> (1, 2, 3) == wrong_id2(1, 2, 3)
True

but no so well for single inputs:

>>> 9 == wrong_id2(9)
False

The problem is that in order to accept multiple inputs, *args must be used, but it has the side-effect of transforming even single-item inputs into a tuple, and the naive wrong_id2 simply returns that tuple:

>>> wrong_id2(9)
(9,)

Now that we know what the problems are, we can write a correct identity function:

def identity(*args):
if len(args) == 1:
# only one item passed in, return that one item
return args[0]
# many items passed in, return them as a tuple
return args

Some simple tests to show it works as advertised:

>>> 'a thing' == identity('a thing')
True

>>> (1, 2, 3) == identity(1, 2, 3)
True

>>> a_tuple = 7, 8, 9
>>> a_dict = {True: 'Python Rocks!', False: 'up is down'}
>>> none = None
>>> (a_tuple, a_dict, none) == identity(a_tuple, a_dict, none)
True
>>> a_tuple is identity(a_tuple)
True
>>> a_dict is identity(a_dict)
True
>>> none is identity(none)
True

DaoWen has made some interesting points against this implementation of identity, the chief one being consistency of return value -- that is, if even the single item case returns a tuple, then we can always treat it the same: call len() on it, put it in a for loop, etc, etc.

While that can be very handy behavior, that is not an identity function, for the simple reason that 1 != (1, ) -- therefore, identity(1) should return 1 and not (1, ).

Is id a python builtin function?

In your example, the reference to cr.id is not a function call. Its accessing a member attribute of the cr variable, which is a placeholder for whatever the crew objects are.

id is the name of a builtin function, yes. But there is no way to know if its being used under the hood in these objects without seeing the actual class definitions.

As an example... if this were, say, a django application, model instances have id member attributes that give you the database id of that record. Its part of the design of the class for that framework.

Even though I am assuming its an attribute... for all we know it could also be a computed property which is similar to a method call that acts like an attribute. It could be doing more logic that it seems when looking at your example.

Lastly, since the cr.id could be anything, it could even be a method and the map is returning a lis of callables: cr.id()

python id() function implementation

There are multiple implementations of python. In cpython, all objects have a standard header and the id is the memory address of that header. References to objects are C pointers to their object header (that same memory address that is the id). You can't use a dunder method to find an object because you need the object pointer to find the dunder methods.

Python is compiled into byte code and that byte code is executed by C. When you call a function like id, that function can be more byte code, but it can also be a C function. Search for "builtin_id" in bltinmodule.c and you'll see the C implementation of id(some_object).

static PyObject *
builtin_id(PyModuleDef *self, PyObject *v)
/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
{
PyObject *id = PyLong_FromVoidPtr(v);

if (id && PySys_Audit("builtins.id", "O", id) < 0) {
Py_DECREF(id);
return NULL;
}

return id;
}

The id function is called with PyObject *v, a pointer to the object whose id should be taken. PyObject is the standard object header used by all python objects. It includes information needed to figure out what type the object really is. The id function turns the object pointer into a python integer with PyLong_FromVoidPtr (the name "long" for a python int is somewhat historical). That's the id you see at the python level.

You can get the cpython source on github and you can read up on C in the python docs at Extending and Embedding the Python Interpreter and Python/C API Reference Manual

Is there an identity function?

The copy(name=None) function on tensors is what you want.

The first example becomes this:

x.name = "x"
y = x.copy("y")

The second example becomes this:

activation = T.dot(feature, filter)
activation.name = "activation"
response = T.nnet.sigmoid(activation) if nonlinear else activation.copy()
response.name = "response"

What is the id( ) function used for?

Your post asks several questions:

What is the number returned from the function?

It is "an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime." (Python Standard Library - Built-in Functions) A unique number. Nothing more, and nothing less. Think of it as a social-security number or employee id number for Python objects.

Is it the same with memory addresses in C?

Conceptually, yes, in that they are both guaranteed to be unique in their universe during their lifetime. And in one particular implementation of Python, it actually is the memory address of the corresponding C object.

If yes, why doesn't the number increase instantly by the size of the data type (I assume that it would be int)?

Because a list is not an array, and a list element is a reference, not an object.

When do we really use id( ) function?

Hardly ever. You can test if two references are the same by comparing their ids, but the is operator has always been the recommended way of doing that. id( ) is only really useful in debugging situations.

`id` function in Python 2.7, `is` operator, object identity and user-defined methods

The Python documentation for the id function states:

Return the "identity" of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

(emphasis mine)

When you do id(Hello.hello) == id(Hello.hello), the method object is created only briefly and is considered "dead" after the first call to 'id'. Because of the call to id, you only need Hello.hello to be alive for a short period of time -- enough to obtain the id. Once you get that id, the object is dead and the second Hello.hello can reuse that address, which makes it appear as if the two objects have the same id.

This is in contrast to doing Hello.hello is Hello.hello -- both instances have to live long enough to be compared to each other, so you end up having two live instances.

If you instead tried:

>>> a = Hello.hello
>>> b = Hello.hello
>>> id(a) == id(b)
False

...you'd get the expected value of False.



Related Topics



Leave a reply



Submit