langShift

Getting Started with the Python Ecosystem

Understand the Python ecosystem from a JavaScript developer's perspective, mastering core tools like pip, venv, and pyenv.

1. Introduction

Why Should JavaScript Developers Learn Python?

As a front-end developer, you may already be proficient in the JavaScript ecosystem, but Python is becoming an indispensable skill in modern development. Here are a few important reasons to learn Python:

  • AI Development: such as training models, data preprocessing, etc.
  • Data Science: such as data analysis, visualization
  • Automation Toolchain: such as web crawlers, office automation scripts

Most importantly: Python is the primary language for AI!

2. Python Language Basics

2.1 Python Introduction

Python is a programming language created by Guido van Rossum in 1991, known for its concise syntax and powerful ecosystem.

The Zen of Python

# The core philosophy of Python: simple and clear
import this
"""
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
"""
# Outputs "The Zen of Python" - the design philosophy of Python
print("The Zen of Python")

Core Comparison with JavaScript

FeatureJavaScriptPythonDescription
Type SystemDynamic TypingDynamic TypingBoth support dynamic typing, but Python has type hints.
ExecutionInterpretedInterpretedBoth require a runtime environment.
Syntax StyleC-styleIndentation-sensitivePython uses indentation instead of curly braces.
Variable Declarationlet/const/varDirect assignmentPython requires no declaration keyword.
StringsSingle/Double quotesSingle/Double/Triple quotesPython supports multi-line strings.
Comments// or /* */# or """Python supports docstrings.

Code Style Comparison Example

// JavaScript style
function calculateArea(width, height) {
const area = width * height;
return area;
}
const result = calculateArea(10, 5);
console.log(`The area is: ${result}`);
# Python style
def calculate_area(width, height):
area = width * height
return area
result = calculate_area(10, 5)
print(f"The area is: {result}")

2.2 Python Installation and Configuration

Installation Method Comparison

Operating SystemJavaScript (Node.js)PythonDescription
WindowsDownload installer from official websiteDownload installer from official websiteBoth have official installers.
macOSHomebrew: brew install nodeHomebrew: brew install pythonRecommended to use a package manager.
LinuxPackage manager or source compilationPackage manager or source compilationSystem package manager is preferred.

Verify Installation

# JavaScript environment verification
node --version
npm --version
# Python environment verification
python --version
# or
python3 --version
pip --version

Environment Variable Configuration

Environment VariableJavaScriptPythonPurpose
PATHNode.js installation directoryPython installation directoryCommand-line access
NODE_PATHGlobal module pathPYTHONPATHModule search path
NPM_CONFIGnpm configurationPIP_CONFIG_FILEPackage manager configuration

3. Python Package Management Ecosystem

3.1 pip - Python's Package Manager

pip is Python's official package manager, similar to npm or yarn in the JavaScript ecosystem.

Core Command Comparison

Functionnpm/yarnpipDescription
Install packagenpm install packagepip install packageInstall a single package.
Global installnpm install -g packagepipx run packagepipx is the recommended tool for installing and running Python CLI applications, avoiding global environment pollution.
Dev dependencynpm install --save-devpip install packagepip itself does not distinguish dependency types, but you can manually manage dev and production dependencies with multiple requirements files.
Uninstall packagenpm uninstall packagepip uninstall packageRemove an installed package.
List packagesnpm listpip listDisplay installed packages.
Update packagenpm update packagepip install --upgrade packageUpgrade to the latest version.

Dependency File Comparison

// package.json (JavaScript)
{
"name": "my-project",
"version": "1.0.0",
"dependencies": {
"express": "^4.18.2",
"axios": "^1.6.0"
},
"devDependencies": {
"jest": "^29.7.0",
"eslint": "^8.55.0"
},
"scripts": {
"start": "node index.js",
"test": "jest"
}
}
# requirements.txt (Python)
# Core dependencies
Flask==2.3.3
requests==2.31.0
pandas==2.1.4
# Development dependencies (usually in requirements-dev.txt)
pytest==7.4.3
black==23.11.0
flake8==6.1.0

Practical Usage Example

# JavaScript project initialization
npm init -y
npm install express axios
npm install --save-dev jest eslint
# Python project initialization
pip install Flask requests pandas
pip install pytest black flake8

3.2 Virtual Environment Management

3.2.1 venv - Python's Built-in Virtual Environment

Virtual environments are a core concept in Python development, similar to the isolation of node_modules in JavaScript, but more thorough.

Concept Comparison

ConceptJavaScriptPythonDescription
Dependency Isolationnode_modules directoryVirtual environment directoryPython's isolation is more complete.
Global Packagesnpm install -gpip installBoth support global installation.
Version Managementpackage.json lockrequirements.txtDependency version control.
Environment SwitchingAutomatic (based on directory)Manual activation/deactivationPython requires explicit activation.

venv Basic Operations

# Create a virtual environment
python -m venv myproject-env
# Activate the virtual environment
# Windows
myproject-env\Scripts\activate
# macOS/Linux
source myproject-env/bin/activate
# Deactivate the virtual environment
deactivate

Project Structure Comparison

# JavaScript Project Structure
my-js-project/
├── node_modules/ # Dependencies
├── package.json # Project configuration
├── package-lock.json # Dependency lock file
├── src/
│ └── index.js
└── README.md
# Python Project Structure
my-python-project/
├── venv/ # Virtual environment (usually not committed to version control)
├── requirements.txt # Dependency list
├── src/
│ └── main.py
└── README.md

Practical Workflow Comparison

# JavaScript Workflow
mkdir my-js-project
cd my-js-project
npm init -y
npm install express
# Start development...
# Python Workflow
mkdir my-python-project
cd my-python-project
python -m venv venv
source venv/bin/activate # or venv\Scripts\activate (Windows)
pip install Flask
# Start development...

3.2.2 pyenv - Python Version Management

pyenv is similar to nvm in the Node.js ecosystem, used for managing multiple Python versions.

Version Management Tool Comparison

Functionnvm (Node.js)pyenv (Python)Description
Install versionnvm install 18.17.0pyenv install 3.11.5Install a specific version.
Switch versionnvm use 18.17.0pyenv global 3.11.5Set the default version.
Local version.nvmrc file.python-version fileProject-level version control.
List versionsnvm listpyenv versionsView installed versions.
Current versionnvm currentpyenv versionDisplay the currently used version.

Installing and Configuring pyenv

# macOS (using Homebrew)
brew install pyenv
# Linux
curl https://pyenv.run | bash
# Add to shell configuration
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(pyenv init -)"' >> ~/.zshrc

pyenv Basic Usage

# View available Python versions
pyenv install --list
# Install a specific version
pyenv install 3.11.5
pyenv install 3.10.12
# Set the global default version
pyenv global 3.11.5
# Set a version for a specific project
cd my-project
pyenv local 3.10.12
# View the current version
pyenv version

Project-level Version Control

# Set the Python version in the project directory
cd my-python-project
pyenv local 3.11.5
# This creates a .python-version file
cat .python-version
# Output: 3.11.5
# Create a virtual environment (using the project-specified Python version)
python -m venv venv
source venv/bin/activate

Best Practice Comparison

Best PracticeJavaScriptPythonReason
Version Lockingpackage-lock.jsonrequirements.txt + virtual environmentEnsure environment consistency.
Dependency Managementnpm cipip install -r requirements.txtFast installation.
Development Environment.env file.env file + virtual environmentEnvironment variable management.
CI/CDnpm ci && npm testpip install && pytestAutomated testing.
DeploymentProduction environment installationVirtual environment packagingEnvironment isolation.

Through the above comparison, you can see that although the Python ecosystem is conceptually similar to JavaScript, it differs in implementation details and best practices. Understanding these differences will help you adapt to the Python development environment more quickly.

4. Development Tool Comparison

4.1 Code Editor/IDE

In modern development, choosing the right editor is crucial for improving development efficiency. Let's look at commonly used tools in JavaScript and Python development.

Mainstream Editor Comparison

EditorJavaScript SupportPython SupportAdvantages
VSCodeNative supportRequires Python extensionLightweight, rich plugins.
PyCharmRequires pluginNative supportPreferred for Python development.
WebStormNative supportRequires pluginPreferred for JavaScript development.
Sublime TextRequires pluginRequires pluginFast, lightweight.
Vim/NeovimRequires configurationRequires configurationEfficient, highly customizable.

VSCode Configuration Comparison

// JavaScript project configuration (.vscode/settings.json)
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"eslint.validate": ["javascript", "typescript"],
"typescript.preferences.importModuleSpecifier": "relative"
}
// Python project configuration (.vscode/settings.json)
{
"python.defaultInterpreterPath": "./venv/bin/python",
"python.formatting.provider": "black",
"python.linting.enabled": true,
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"editor.formatOnSave": true
}

Recommended VSCode Extensions

FunctionJavaScript ExtensionPython ExtensionDescription
Syntax HighlightingBuilt-inPythonBasic syntax support.
IntelliSenseTypeScriptPylanceCode completion and type checking.
Code FormattingPrettierBlackUnify code style.
Code LintingESLintFlake8/RuffCode quality checking.
DebuggingNode.js DebuggerPython DebuggerBreakpoint debugging.
TestingJest RunnerPython Test ExplorerTest runner.

5. Project Structure Comparison

5.1 Python Project Structure

Python projects have a standard directory structure. Let's compare the project organization of JavaScript and Python.

Standard Project Structure Comparison

Directory/FileJavaScript ProjectPython ProjectDescription
Configuration Filepackage.jsonpyproject.tomlProject metadata and dependencies.
Dependency Lockpackage-lock.jsonrequirements.txtPrecise version control.
Source Codesrc/src/ or project rootMain code files.
Test Files__tests__/ or test/tests/Test code.
Documentationdocs/docs/Project documentation.
Build Outputdist/build/Build artifacts.
Environment Config.env.env (with python-dotenv library)Environment variables.

Typical Project Structure Example

# JavaScript Project Structure
my-js-app/
├── package.json # Project configuration
├── package-lock.json # Dependency lock
├── .eslintrc.js # ESLint configuration
├── .prettierrc # Prettier configuration
├── tsconfig.json # TypeScript configuration
├── src/
│ ├── components/ # React components
│ ├── utils/ # Utility functions
│ ├── types/ # TypeScript types
│ └── index.ts # Entry file
├── tests/
│ └── components.test.ts # Test file
├── docs/ # Documentation
├── dist/ # Build output
└── README.md
# Python Project Structure
my-python-app/
├── pyproject.toml # Project configuration
├── requirements.txt # Dependency list
├── requirements-dev.txt # Development dependencies
├── .flake8 # Flake8 configuration
├── .env # Environment variables
├── src/
│ └── my_python_app/ # Package directory
│ ├── __init__.py # Package initialization
│ ├── core/ # Core modules
│ ├── utils/ # Utility functions
│ └── main.py # Entry file
├── tests/
│ ├── __init__.py # Test package initialization
│ ├── test_core.py # Core tests
│ └── conftest.py # pytest configuration
├── docs/ # Documentation
├── build/ # Build output
└── README.md

5.2 Dependency Management and Project Configuration

Modern Python projects are moving towards using a single configuration file, pyproject.toml, which is similar to package.json in the JavaScript ecosystem. This file can define project metadata, dependencies, and configurations for various tools (like formatters and linters).

Dependency Management Tool Comparison

ToolJavaScript EquivalentFeaturesUse Case
pip + requirements.txtnpm + package.jsonTraditional, simple, directLegacy projects or small scripts.
PoetryYarn / npmpyproject.toml driven, integrates dependency, environment, and packaging managementRecommended for new projects.
pip-toolsnpm ci / package-lock.jsonCompiles requirements.txt from pyproject.toml or .in filesRequires precise control over dependency files.
pipenvnpmAutomatically manages virtual environments and dependenciesStill used in some workflows.

Dependency File Format Comparison

// package.json (JavaScript)
{
"name": "my-app",
"version": "1.0.0",
"description": "A sample application",
"main": "src/index.js",
"scripts": {
"start": "node src/index.js",
"test": "jest",
"build": "webpack",
"lint": "eslint src/",
"format": "prettier --write src/"
},
"dependencies": {
"express": "^4.18.2",
"axios": "^1.6.0"
},
"devDependencies": {
"jest": "^29.7.0",
"eslint": "^8.55.0",
"prettier": "^3.1.0"
},
"engines": {
"node": ">=18.0.0"
}
}
# pyproject.toml (Python - Poetry)
[tool.poetry]
name = "my-python-app"
version = "0.1.0"
description = "A sample Python application"
authors = ["Your Name <your.email@example.com>"]
readme = "README.md"
packages = [{include = "my_python_app", from = "src"}]
[tool.poetry.dependencies]
python = "^3.8"
flask = "^2.3.3"
requests = "^2.31.0"
[tool.poetry.group.dev.dependencies]
pytest = "^7.4.3"
black = "^23.11.0"
flake8 = "^6.1.0"
[tool.poetry.scripts]
start = "my_python_app.main:main"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

Dependency Installation and Update Comparison

# JavaScript Dependency Management
npm install # Install all dependencies
npm install express # Install production dependency
npm install --save-dev jest # Install development dependency
npm update # Update dependencies
npm audit # Security audit
npm outdated # Check for outdated dependencies
# Python Dependency Management (pip)
pip install -r requirements.txt # Install all dependencies
pip install flask # Install a package
pip install pytest --user # User-level installation
pip install --upgrade flask # Update a package
pip list --outdated # Check for outdated dependencies
# Python Dependency Management (Poetry)
poetry install # Install all dependencies
poetry add flask # Add production dependency
poetry add --group dev pytest # Add development dependency
poetry update # Update dependencies
poetry show --tree # Show dependency tree

6. Practical Exercises

6.1 Environment Setup Exercise

Let's get familiar with setting up a Python development environment through practical exercises.

Exercise 1: Create Your First Python Project

# 1. Create the project directory
mkdir my-first-python-project
cd my-first-python-project
# 2. Set the Python version with pyenv
pyenv local 3.11.5
# 3. Create a virtual environment
python -m venv venv
# 4. Activate the virtual environment
# Windows
venv\Scripts\activate
# macOS/Linux
source venv/bin/activate
# 5. Install base packages
pip install requests flask pytest black flake8
# 6. Create requirements.txt
pip freeze > requirements.txt

Comparison: JavaScript Project Creation

# 1. Create the project directory
mkdir my-first-js-project
cd my-first-js-project
# 2. Initialize npm project
npm init -y
# 3. Install base packages
npm install express axios
npm install --save-dev jest eslint prettier
# 4. Create .gitignore
echo "node_modules/" > .gitignore
echo "dist/" >> .gitignore

Exercise 2: Configure the Development Environment

# Python Project Configuration
# 1. Create project structure
mkdir -p src/my_app tests docs
# 2. Create configuration files
touch pyproject.toml .flake8 .env
# 3. Configure VSCode
mkdir .vscode
touch .vscode/settings.json .vscode/launch.json
# JavaScript Project Configuration
# 1. Create project structure
mkdir -p src/components src/utils tests docs
# 2. Create configuration files
touch .eslintrc.js .prettierrc tsconfig.json
# 3. Configure VSCode
mkdir .vscode
touch .vscode/settings.json .vscode/launch.json

7. Summary and Next Steps

7.1 Core Concepts of the Python Ecosystem Summary

Through this module, you have mastered the core concepts of the Python ecosystem:

Core Tool Comparison Summary

ConceptJavaScript EquivalentPython ToolKey Difference
RuntimeNode.jsPython InterpreterPython requires explicit version management.
Package Managernpm/yarnpip/poetryPython's toolchain is more fragmented, but both pip and poetry provide dependency management.
Dependency Isolationnode_modulesVirtual EnvironmentPython's virtual environment is completely isolated.
Version ManagementnvmpyenvSimilar functionality, different syntax.
Code QualityESLint + PrettierFlake8 + BlackPython tools are more focused.

7.2 Next Module Preview

In the next module, we will dive deep into Python's core syntax, including:

Module 1: Python Syntax Basics

  • Variables and data types
  • Control flow statements
  • Function definition and invocation
  • List, dictionary, and set operations
  • File operations and exception handling

Learning Objectives

  • Master basic Python syntax
  • Understand syntax differences with JavaScript
  • Be able to write simple Python programs
  • Build a solid foundation for further learning

Recommended Learning Resources

Resource TypeRecommended ContentSuitable Stage
Official DocumentationPython Official TutorialBasic learning
Online CoursesReal Python, Python.orgSystematic learning
Practice PlatformsLeetCode, HackerRankAlgorithm practice
Open Source ProjectsGitHub Python ProjectsPractical experience

Congratulations on completing the introduction to the Python ecosystem! You have now mastered the core tools and concepts of the Python development environment. In the following lessons, we will delve into various aspects of the Python language to help you understand Python code as quickly as possible.

Remember: Learning Python is not about replacing JavaScript, but about expanding your tech stack, enabling you to handle more types of development tasks. Both languages have their own strengths, and using them together will make you a more powerful developer.