.PY Python Source Code
.py

Python Source Code

Python (.py) files contain interpreted source code using indentation-based syntax, running on CPython, PyPy, or other Python runtimes. FileDex provides local Python format reference and analysis in your browser — no uploads, no server processing.

بنية الصيغة
Header schema
Records structured data
Programming LanguageText FormatInterpretedDynamic Typing1991
بواسطة FileDex
غير قابل للتحويل

Source code format. Conversion is not applicable.

أسئلة شائعة

What is the difference between Python 2 and Python 3?

Python 3 made breaking changes: print became a function, strings are Unicode by default, and integer division returns floats. Python 2 reached end-of-life in January 2020 and receives no security patches. All new projects should use Python 3.10 or later.

How do I run a .py file from the command line?

Type `python3 script.py` in the terminal (or `python script.py` on Windows). On Unix systems, you can also add `#!/usr/bin/env python3` as the first line, make the file executable with `chmod +x script.py`, and run it directly with `./script.py`.

Why does my Python file show IndentationError?

Python uses whitespace to define code blocks. Mixing tabs and spaces within the same block triggers IndentationError or TabError in Python 3. Configure your editor to insert spaces (4 per level is standard) and run `python3 -tt script.py` to flag inconsistent indentation.

How do I create a virtual environment for a Python project?

Run `python3 -m venv .venv` to create a virtual environment, then activate it with `source .venv/bin/activate` on Unix or `.venv\Scripts\activate` on Windows. Install dependencies with `pip install -r requirements.txt`. The uv tool provides a faster alternative: `uv venv && uv pip install -r requirements.txt`.

ما يميز .PY

What is a PY file?

PY files contain Python source code — a high-level, interpreted programming language created by Guido van Rossum and first released in 1991. Python is designed for readability, using indentation to define code blocks instead of curly braces. It is consistently ranked the most popular programming language globally, driven by its dominance in data science, machine learning, automation, and web development.

اكتشف التفاصيل التقنية

Python's philosophy is captured in the Zen of Python: "Readability counts," "Simple is better than complex," and "There should be one — and preferably only one — obvious way to do it." PY files run on the CPython interpreter by default, with no compilation step required.

How to open PY files

  • Python interpreterpython script.py to execute from the terminal
  • VS Code (Windows, macOS, Linux) — IntelliSense, debugging, virtual environment support
  • PyCharm (Windows, macOS, Linux) — The most feature-rich Python IDE
  • IDLE — Python's built-in editor, installed with Python
  • Jupyter Notebook / JupyterLab — Interactive environment popular in data science

Technical specifications

Property Value
Encoding UTF-8 (default since Python 3)
Typing Dynamic with optional type hints (PEP 484+)
Paradigm Multi-paradigm (OOP, functional, procedural)
Interpreter CPython (official), PyPy (faster JIT), Jython (JVM)
Package Manager pip (standard), conda (data science), uv (fast Rust-based)
Current Version Python 3.13+

Common use cases

  • Data science: Pandas, NumPy, matplotlib, Polars for data analysis and visualization
  • Machine learning / AI: TensorFlow, PyTorch, scikit-learn, Hugging Face
  • Web development: Django (full-stack), Flask (microframework), FastAPI (async APIs)
  • Automation: Scripts for file processing, web scraping (BeautifulSoup, Playwright), task scheduling
  • Scientific computing: SciPy, Astropy, BioPython for domain-specific research
  • DevOps: Ansible playbooks, AWS Lambda functions, CLI tools

Python code example

# Type hints (optional but recommended)
def word_count(text: str) -> dict[str, int]:
    words = text.lower().split()
    counts: dict[str, int] = {}
    for word in words:
        counts[word] = counts.get(word, 0) + 1
    return counts

# List comprehension
squares = [x**2 for x in range(10) if x % 2 == 0]

# Async function
import asyncio

async def fetch_data(url: str) -> str:
    # ... async HTTP call
    pass

Virtual environments

Python projects use virtual environments to isolate dependencies:

python -m venv .venv          # Create environment
source .venv/bin/activate     # Activate (Unix)
.venv\Scripts\activate        # Activate (Windows)
pip install -r requirements.txt

This prevents version conflicts between projects. Modern tools like uv handle environments and dependencies significantly faster than pip.

Python 2 vs Python 3

Python 2 reached end-of-life in January 2020 and should never be used for new projects. Python 3 introduced breaking changes: print became a function, strings are Unicode by default, and integer division returns floats. Any .py file that starts with print "hello" (no parentheses) is Python 2 code and requires migration.

Security considerations

Python scripts executed from untrusted sources can run arbitrary system commands. Use subprocess with a list of arguments (not a shell string) to prevent shell injection. When using pickle for serialization, never deserialize data from untrusted sources — pickle can execute arbitrary code during deserialization. Prefer JSON or msgpack for data interchange with external systems.

Type hints and static analysis

Python's optional type hint system (introduced in Python 3.5, mature in 3.10+) allows tools like mypy, pyright, and Pylance (VS Code) to catch type errors before runtime. Type hints do not affect execution — they are purely for developer tooling. Modern Python codebases increasingly use type hints for better IDE support and fewer runtime bugs.

صيغ ذات صلة

المرجع التقني

نوع MIME
text/x-python
المطوّر
Guido van Rossum
سنة التقديم
1991
معيار مفتوح
نعم

البنية الثنائية

Python files are plain-text source code encoded in UTF-8 by default (since Python 3). There are no binary magic bytes. Files may begin with an optional shebang line `#!/usr/bin/env python3` for direct execution on Unix-like systems, and an optional encoding declaration `# -*- coding: utf-8 -*-` or `# coding: utf-8` on the first or second line (PEP 263). Python 2 defaulted to ASCII encoding, making the coding declaration mandatory for non-ASCII source. Python uses significant whitespace — indentation defines code blocks, and mixing tabs and spaces raises TabError in Python 3. Line endings (LF or CRLF) are both accepted, but LF is conventional.

1991Guido van Rossum releases Python 0.9.0 with classes, exception handling, and functions2000Python 2.0 adds list comprehensions, garbage collection, and Unicode string support2008Python 3.0 released with breaking changes: print() as function, Unicode strings by default, integer division returns float2015Python 3.5 introduces type hints (PEP 484) and async/await syntax (PEP 492)2020Python 2 reaches end-of-life — no further security patches or releases2022Python 3.11 ships with 10-60% speed improvements from the Faster CPython project2024Python 3.13 introduces experimental JIT compiler and free-threaded mode (no GIL)
Format Python code with Black أخرى
black --line-length 88 input.py

Black is an opinionated formatter that enforces a single consistent style. --line-length 88 is the default. Black modifies files in place and produces deterministic output — two developers formatting the same code always get identical results.

Lint and fix with Ruff أخرى
ruff check --fix input.py

Ruff is a Python linter written in Rust that runs 10-100x faster than Flake8 or Pylint. --fix automatically resolves fixable violations including unused imports, missing trailing commas, and incorrect string quotes.

Type check with mypy أخرى
mypy --strict input.py

--strict enables all optional type-checking flags: disallow untyped defs, no implicit optional, warn on unreachable code. Reports type errors that would otherwise surface as runtime exceptions.

Compile to standalone executable with PyInstaller أخرى
pyinstaller --onefile --name myapp input.py

Bundles the Python interpreter, all imported modules, and the script into a single executable file. --onefile creates one binary instead of a directory. --name sets the output filename.

PY COMPILED BYTECODE (.PYC) transcode lossless Python compiles source to bytecode (.pyc) for faster subsequent imports. The py_compile module generates .pyc files explicitly, which CPython stores in __pycache__ directories. Bytecode is version-specific and not portable across Python releases.
PY STANDALONE EXECUTABLE render lossless PyInstaller bundles a Python script with its interpreter and dependencies into a single executable for distribution to users who do not have Python installed. This eliminates the runtime dependency at the cost of larger file size (50-150MB).
PY JUPYTER NOTEBOOK (.IPYNB) export lossless Data scientists often convert linear scripts into interactive notebooks for cell-by-cell execution, inline visualization, and documentation mixing code with Markdown explanations.
عالي

نقاط الضعف

  • Arbitrary code execution: Python scripts run with full system access — importing or executing untrusted .py files can read/write files, spawn processes, and access the network
  • Pickle deserialization attacks: pickle.load() on untrusted data executes arbitrary Python code during object reconstruction via __reduce__
  • eval/exec injection: passing unsanitized user input to eval() or exec() allows arbitrary code execution
  • Supply chain attacks via PyPI: malicious packages with typosquatted names or compromised maintainer accounts inject code into pip install workflows
  • Subprocess shell injection: subprocess.run(user_input, shell=True) allows command injection if the input is not sanitized

الحماية: FileDex processes Python files locally in the browser as static text — no Python interpreter runs, no imports are resolved, no code is executed. Files are analyzed for format identification only.

CPython أداة
The official reference Python interpreter, written in C
pip أداة
Default Python package installer, installs from PyPI
uv أداة
Extremely fast Python package manager and resolver written in Rust
Black أداة
Opinionated Python code formatter that enforces a single consistent style
Ruff أداة
Extremely fast Python linter and formatter written in Rust
mypy أداة
Static type checker for Python using PEP 484 type hints
PyInstaller أداة
Bundles Python scripts into standalone executables for Windows, macOS, and Linux