Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python is it bad to create an attribute called 'id'?

Tags:

python

I know that there's a function called id so I wouldn't create a function or a variable called id, but what about an attribute on an object?

like image 237
guidoism Avatar asked Aug 16 '10 22:08

guidoism


People also ask

Can I use id as a variable name in Python?

id() is a function in python, so it's recommend not to use a variable named id. Bearing that in mind, that applies to all functions that you might use... a variable shouldn't have the same name as a function.

Why do we use id in Python?

Definition and Usage. The id() function returns a unique id for the specified object. All objects in Python has its own unique id. The id is assigned to the object when it is created.

Is id unique in Python?

The id is unique only as long as an object is alive. Objects that have no references left to them are removed from memory, allowing the id() value to be re-used for another object, hence the non-overlapping lifetimes wording. Note that this applies to CPython only, the standard implementation provided by python.org.

Can I use id in Python?

id() is an inbuilt function in Python. As we can see the function accepts a single parameter and is used to return the identity of an object. This identity has to be unique and constant for this object during the lifetime. Two objects with non-overlapping lifetimes may have the same id() value.


2 Answers

I do this frequently for classes that abstract database tables where there is often a field called id because there is no reasonable chance of a name conflict. Be advised that some synatax highlighters will mark it as a builtin function.

like image 44
aaronasterling Avatar answered Sep 21 '22 21:09

aaronasterling


That's ok, and is pretty common. For example, objects mapped to a database record will often have an "id" attribute mapped to the database "id" column value.

Attributes are always "namespaced" so you have to refer to them via self.id or obj.id so there's no conflict with the built-in function.

like image 100
Matt Good Avatar answered Sep 17 '22 21:09

Matt Good