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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With