Python Fundamentals

Coding Conventions

It’s commonplace to have to adhere to a standard when writing your code. For Python, the common standard is called “PEP 8”. You can read more about it here, but some important takeaways are:

  • Comment your code. Not every line, but everything that you think may require explanation, or multi-line algorithms. And at the very least, every function should have a docstring description
  • Indentation in your IDE should be set to 4 spaces. No tabs.
  • Variable and function names should match the project you’re working in. If it’s a blank slate, start with “lower_case_with_underscores”
  • Constants should be declared at the top of the file and be in CAPITAL_LETTERS_WITH_UNDERSCORE

Everyone has their own style with other things. Some people prefer to call a dictionary with “dict”, others prefer “{}”. And everyone thinks their way is best. If you adhere to what others are writing, and your code is easily understandable, then very rarely will anyone quibble too much.

Accessors

Within a class it’s usually safer to not access variables directly. For this reason, you’ll often see class methods starting with “get” or “set”. Using these methods, you can also implement validation upon the “setting” of a value.

 Previous: Intro to Python – Part 2 Next: Intro to Pymel