langShiftlangShift

Module 10: Common Pitfalls

From a JavaScript developer's perspective, this module analyzes common conceptual pitfalls and error-prone points in Python.

1. Introduction

When you switch from one language to another, the trickiest parts are often not the new syntax, but the "gotchas" that seem similar but behave completely differently. These subtle differences can lead to hard-to-detect bugs and confusion.

This module is specifically designed for you—a developer transitioning from JavaScript to Python—to sort out some of the most common conceptual pitfalls.

💡 Learning Strategy: Don't just memorize. Understand the "why" behind each pitfall and compare it to JavaScript's behavior. This way, you will naturally avoid them in your actual coding.

2. Truthy vs. Falsy

In Python, empty collection types (like lists, dictionaries, tuples) are considered "falsy." This is a significant difference from JavaScript's behavior, where an empty array [] and an empty object {} are both "truthy."

Loading editor...

3. this vs. self

In JavaScript class methods, this is a keyword whose value is determined when the function is called. In Python instance methods, the first parameter (named self by convention) explicitly represents the instance itself, and it is not a keyword.

Loading editor...

4. Variable Scope

JavaScript (ES6+) has block-level scope (defined by {}), while Python's scope is based on functions (or classes, modules). Variables defined in code blocks like for loops will "leak" into the outer scope in Python.

Loading editor...

5. Mutable Default Arguments

This is a very classic and notorious "gotcha" in Python. If a function's default argument is a mutable object (like a list or dictionary), that object will be shared across all calls. This is completely different from JavaScript's behavior.

Loading editor...

6. null/undefined vs. None

JavaScript has two values to represent "nothing": null (representing an "intentionally set empty value") and undefined (representing "not defined"). In Python, there is only one corresponding concept: None.

Loading editor...

7. Loop Variable Capture

This is a side effect of Python's scoping rules, often occurring in closures or lambda functions.

Loading editor...

8. Assignment vs Copying

In Python, assignment (=) never copies an object; it only creates a new reference (alias). This is consistent with JavaScript's object assignment behavior, but can be a trap for developers used to certain C++ behaviors.

Loading editor...

8. Summary

Understanding and mastering these differences will help you write robust, unsurprising Python code more quickly. When you encounter unexpected behavior, it's a good idea to come back to this list and check if you've fallen into one of these "traps."