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 clearimport 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 Pythonprint("The Zen of Python")
Core Comparison with JavaScript
Feature | JavaScript | Python | Description |
---|---|---|---|
Type System | Dynamic Typing | Dynamic Typing | Both support dynamic typing, but Python has type hints. |
Execution | Interpreted | Interpreted | Both require a runtime environment. |
Syntax Style | C-style | Indentation-sensitive | Python uses indentation instead of curly braces. |
Variable Declaration | let/const/var | Direct assignment | Python requires no declaration keyword. |
Strings | Single/Double quotes | Single/Double/Triple quotes | Python supports multi-line strings. |
Comments | // or /* */ | # or """ | Python supports docstrings. |
Code Style Comparison Example
// JavaScript stylefunction calculateArea(width, height) {const area = width * height;return area;}const result = calculateArea(10, 5);console.log(`The area is: ${result}`);
# Python styledef calculate_area(width, height):area = width * heightreturn arearesult = calculate_area(10, 5)print(f"The area is: {result}")
2.2 Python Installation and Configuration
Installation Method Comparison
Operating System | JavaScript (Node.js) | Python | Description |
---|---|---|---|
Windows | Download installer from official website | Download installer from official website | Both have official installers. |
macOS | Homebrew: brew install node | Homebrew: brew install python | Recommended to use a package manager. |
Linux | Package manager or source compilation | Package manager or source compilation | System package manager is preferred. |
Verify Installation
# JavaScript environment verificationnode --versionnpm --version# Python environment verificationpython --version# orpython3 --versionpip --version
Environment Variable Configuration
Environment Variable | JavaScript | Python | Purpose |
---|---|---|---|
PATH | Node.js installation directory | Python installation directory | Command-line access |
NODE_PATH | Global module path | PYTHONPATH | Module search path |
NPM_CONFIG | npm configuration | PIP_CONFIG_FILE | Package 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
Function | npm/yarn | pip | Description |
---|---|---|---|
Install package | npm install package | pip install package | Install a single package. |
Global install | npm install -g package | pipx run package | pipx is the recommended tool for installing and running Python CLI applications, avoiding global environment pollution. |
Dev dependency | npm install --save-dev | pip install package | pip itself does not distinguish dependency types, but you can manually manage dev and production dependencies with multiple requirements files. |
Uninstall package | npm uninstall package | pip uninstall package | Remove an installed package. |
List packages | npm list | pip list | Display installed packages. |
Update package | npm update package | pip install --upgrade package | Upgrade 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 dependenciesFlask==2.3.3requests==2.31.0pandas==2.1.4# Development dependencies (usually in requirements-dev.txt)pytest==7.4.3black==23.11.0flake8==6.1.0
Practical Usage Example
# JavaScript project initializationnpm init -ynpm install express axiosnpm install --save-dev jest eslint# Python project initializationpip install Flask requests pandaspip 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
Concept | JavaScript | Python | Description |
---|---|---|---|
Dependency Isolation | node_modules directory | Virtual environment directory | Python's isolation is more complete. |
Global Packages | npm install -g | pip install | Both support global installation. |
Version Management | package.json lock | requirements.txt | Dependency version control. |
Environment Switching | Automatic (based on directory) | Manual activation/deactivation | Python requires explicit activation. |
venv Basic Operations
# Create a virtual environmentpython -m venv myproject-env# Activate the virtual environment# Windowsmyproject-env\Scripts\activate# macOS/Linuxsource myproject-env/bin/activate# Deactivate the virtual environmentdeactivate
Project Structure Comparison
# JavaScript Project Structuremy-js-project/├── node_modules/ # Dependencies├── package.json # Project configuration├── package-lock.json # Dependency lock file├── src/│ └── index.js└── README.md# Python Project Structuremy-python-project/├── venv/ # Virtual environment (usually not committed to version control)├── requirements.txt # Dependency list├── src/│ └── main.py└── README.md
Practical Workflow Comparison
# JavaScript Workflowmkdir my-js-projectcd my-js-projectnpm init -ynpm install express# Start development...# Python Workflowmkdir my-python-projectcd my-python-projectpython -m venv venvsource 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
Function | nvm (Node.js) | pyenv (Python) | Description |
---|---|---|---|
Install version | nvm install 18.17.0 | pyenv install 3.11.5 | Install a specific version. |
Switch version | nvm use 18.17.0 | pyenv global 3.11.5 | Set the default version. |
Local version | .nvmrc file | .python-version file | Project-level version control. |
List versions | nvm list | pyenv versions | View installed versions. |
Current version | nvm current | pyenv version | Display the currently used version. |
Installing and Configuring pyenv
# macOS (using Homebrew)brew install pyenv# Linuxcurl https://pyenv.run | bash# Add to shell configurationecho 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrcecho 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrcecho 'eval "$(pyenv init -)"' >> ~/.zshrc
pyenv Basic Usage
# View available Python versionspyenv install --list# Install a specific versionpyenv install 3.11.5pyenv install 3.10.12# Set the global default versionpyenv global 3.11.5# Set a version for a specific projectcd my-projectpyenv local 3.10.12# View the current versionpyenv version
Project-level Version Control
# Set the Python version in the project directorycd my-python-projectpyenv local 3.11.5# This creates a .python-version filecat .python-version# Output: 3.11.5# Create a virtual environment (using the project-specified Python version)python -m venv venvsource venv/bin/activate
Best Practice Comparison
Best Practice | JavaScript | Python | Reason |
---|---|---|---|
Version Locking | package-lock.json | requirements.txt + virtual environment | Ensure environment consistency. |
Dependency Management | npm ci | pip install -r requirements.txt | Fast installation. |
Development Environment | .env file | .env file + virtual environment | Environment variable management. |
CI/CD | npm ci && npm test | pip install && pytest | Automated testing. |
Deployment | Production environment installation | Virtual environment packaging | Environment 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
Editor | JavaScript Support | Python Support | Advantages |
---|---|---|---|
VSCode | Native support | Requires Python extension | Lightweight, rich plugins. |
PyCharm | Requires plugin | Native support | Preferred for Python development. |
WebStorm | Native support | Requires plugin | Preferred for JavaScript development. |
Sublime Text | Requires plugin | Requires plugin | Fast, lightweight. |
Vim/Neovim | Requires configuration | Requires configuration | Efficient, 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
Function | JavaScript Extension | Python Extension | Description |
---|---|---|---|
Syntax Highlighting | Built-in | Python | Basic syntax support. |
IntelliSense | TypeScript | Pylance | Code completion and type checking. |
Code Formatting | Prettier | Black | Unify code style. |
Code Linting | ESLint | Flake8/Ruff | Code quality checking. |
Debugging | Node.js Debugger | Python Debugger | Breakpoint debugging. |
Testing | Jest Runner | Python Test Explorer | Test 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/File | JavaScript Project | Python Project | Description |
---|---|---|---|
Configuration File | package.json | pyproject.toml | Project metadata and dependencies. |
Dependency Lock | package-lock.json | requirements.txt | Precise version control. |
Source Code | src/ | src/ or project root | Main code files. |
Test Files | __tests__/ or test/ | tests/ | Test code. |
Documentation | docs/ | docs/ | Project documentation. |
Build Output | dist/ | build/ | Build artifacts. |
Environment Config | .env | .env (with python-dotenv library) | Environment variables. |
Typical Project Structure Example
# JavaScript Project Structuremy-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 Structuremy-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
Tool | JavaScript Equivalent | Features | Use Case |
---|---|---|---|
pip + requirements.txt | npm + package.json | Traditional, simple, direct | Legacy projects or small scripts. |
Poetry | Yarn / npm | pyproject.toml driven, integrates dependency, environment, and packaging management | Recommended for new projects. |
pip-tools | npm ci / package-lock.json | Compiles requirements.txt from pyproject.toml or .in files | Requires precise control over dependency files. |
pipenv | npm | Automatically manages virtual environments and dependencies | Still 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 Managementnpm install # Install all dependenciesnpm install express # Install production dependencynpm install --save-dev jest # Install development dependencynpm update # Update dependenciesnpm audit # Security auditnpm outdated # Check for outdated dependencies# Python Dependency Management (pip)pip install -r requirements.txt # Install all dependenciespip install flask # Install a packagepip install pytest --user # User-level installationpip install --upgrade flask # Update a packagepip list --outdated # Check for outdated dependencies# Python Dependency Management (Poetry)poetry install # Install all dependenciespoetry add flask # Add production dependencypoetry add --group dev pytest # Add development dependencypoetry update # Update dependenciespoetry 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 directorymkdir my-first-python-projectcd my-first-python-project# 2. Set the Python version with pyenvpyenv local 3.11.5# 3. Create a virtual environmentpython -m venv venv# 4. Activate the virtual environment# Windowsvenv\Scripts\activate# macOS/Linuxsource venv/bin/activate# 5. Install base packagespip install requests flask pytest black flake8# 6. Create requirements.txtpip freeze > requirements.txt
Comparison: JavaScript Project Creation
# 1. Create the project directorymkdir my-first-js-projectcd my-first-js-project# 2. Initialize npm projectnpm init -y# 3. Install base packagesnpm install express axiosnpm install --save-dev jest eslint prettier# 4. Create .gitignoreecho "node_modules/" > .gitignoreecho "dist/" >> .gitignore
Exercise 2: Configure the Development Environment
# Python Project Configuration# 1. Create project structuremkdir -p src/my_app tests docs# 2. Create configuration filestouch pyproject.toml .flake8 .env# 3. Configure VSCodemkdir .vscodetouch .vscode/settings.json .vscode/launch.json
# JavaScript Project Configuration# 1. Create project structuremkdir -p src/components src/utils tests docs# 2. Create configuration filestouch .eslintrc.js .prettierrc tsconfig.json# 3. Configure VSCodemkdir .vscodetouch .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
Concept | JavaScript Equivalent | Python Tool | Key Difference |
---|---|---|---|
Runtime | Node.js | Python Interpreter | Python requires explicit version management. |
Package Manager | npm/yarn | pip/poetry | Python's toolchain is more fragmented, but both pip and poetry provide dependency management. |
Dependency Isolation | node_modules | Virtual Environment | Python's virtual environment is completely isolated. |
Version Management | nvm | pyenv | Similar functionality, different syntax. |
Code Quality | ESLint + Prettier | Flake8 + Black | Python 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 Type | Recommended Content | Suitable Stage |
---|---|---|
Official Documentation | Python Official Tutorial | Basic learning |
Online Courses | Real Python, Python.org | Systematic learning |
Practice Platforms | LeetCode, HackerRank | Algorithm practice |
Open Source Projects | GitHub Python Projects | Practical 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.
JavaScript to Python Learning Module
A Python learning module designed for developers with a JavaScript background, enabling rapid mastery of Python programming through comparative learning.
JavaScript vs Python Syntax Comparison
An in-depth comparison of the syntax differences between the two languages from a JavaScript developer's perspective, to quickly master Python syntax.