0

I checked the Python style guide, and I found no specific references to having instance variable names with reserved words e.g. self.type, self.class, etc.

What's the best practice for this?

asked Oct 10, 2016 at 18:16
4
  • 1
    The discussion in the comments of Why can't attribute names be Python keywords? suggests that you should append an underscore. Commented Oct 10, 2016 at 18:19
  • class is a keyword. You cannot use it. type is not a keyword, so you can. self.type = something is actually not even a problem, but a variable type = x is a bigger probem because it hides the built-in type Commented Oct 10, 2016 at 18:20
  • I see. Thanks a lot! Commented Oct 10, 2016 at 18:22
  • BTW, here's the list of all keywords: docs.python.org/3/reference/lexical_analysis.html#keywords Commented Oct 10, 2016 at 18:24

1 Answer 1

2

Avoid it if possible.

You can get and set such attributes via getattr and setattr, but they can't be accessed with ordinary dot syntax (something like obj.class is a syntax error), so they're a pain to use.

As Aurora0001 mentioned in a comment, a convention if you "need" to use them is to append an underscore. The most common reason to "need" to have such attributes is that they're generated programatically from an external data source.

(Note that type is not a keyword, so you can do self.type just fine.)

answered Oct 10, 2016 at 18:19
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.