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

Question:

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?

Asked By: guidoism

||

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.

Answered By: 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.

Answered By: Matt Good

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

Answered By: bukzor
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.