guidoism
guidoism

Reputation: 8158

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

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?

Upvotes: 45

Views: 8158

Answers (3)

bukzor
bukzor

Reputation: 38532

As others have said, it's perfectly fine to have an id attribute, although many consider a bad practice for database design. But that's another question.

If you care about conventions in general, you should check out pylint. This tool analyses your code for errors and also convention problems.

http://www.logilab.org/857

Upvotes: 2

aaronasterling
aaronasterling

Reputation: 71054

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.

Upvotes: 8

Matt Good
Matt Good

Reputation: 3117

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.

Upvotes: 44

Related Questions