25 nooby Python habits you need to ditch

mCoding2 minutes read

Use f strings for string formatting, utilize a with statement to close files, opt for context managers, avoid bare except clauses, understand XOR, be cautious with default mutable arguments, use comprehensions, but don't overuse them.

Insights

  • Use f strings for string formatting instead of the plus sign; they are more readable and less error-prone.
  • Avoid manually closing files; utilize a with statement to ensure proper closure even in case of exceptions.

Get key ideas from YouTube videos. It’s free

Recent questions

  • How should I format strings in Python?

    Use f strings for string formatting instead of the plus sign; they are more readable and less error-prone.

  • What is the best way to handle file closure in Python?

    Avoid manually closing files; utilize a with statement to ensure proper closure even in case of exceptions.

  • How should I handle resource management in Python?

    Opt for context managers over try-finally for resource handling in Python.

  • What is the importance of specific exception handling in Python?

    Refrain from using bare except clauses; catch specific exceptions to avoid unintended catches like keyboard interrupts.

  • When should I use list comprehensions in Python?

    Utilize comprehensions, including list, dictionary, set, and generator comprehensions, for concise and clear code.

Related videos

Summary

00:00

Python Best Practices for Clean Code

  • Use f strings for string formatting instead of the plus sign; they are more readable and less error-prone.
  • Avoid manually closing files; utilize a with statement to ensure proper closure even in case of exceptions.
  • Opt for context managers over try-finally for resource handling in Python.
  • Refrain from using bare except clauses; catch specific exceptions to avoid unintended catches like keyboard interrupts.
  • Understand that the caret symbol (^) signifies bitwise xor, not exponentiation.
  • Be cautious with default mutable arguments in functions to prevent sharing the same list across calls.
  • Utilize comprehensions, including list, dictionary, set, and generator comprehensions, for concise and clear code.
  • Avoid excessive use of comprehensions; not every loop needs to be turned into a comprehension.
Channel avatarChannel avatarChannel avatarChannel avatarChannel avatar

Try it yourself — It’s free.