AsPython
Developers, are you often troubled by the long wait for dependency installation, the cumbersome management of virtual environments, or the problem of "inconsistency in environments" when sharing scripts?
In recent years, aUV
Tools are quietly emerging. It is not only known for its rapid installation and dependence, but also reconstructed through a series of innovative designs.Python
The script's running logic.
This article mainly introducesUV
Three practical tips from"Dependency is code"arrive"Dynamic Environment Isolation", experience real"Write and run"efficient development model.
1. Speedy startup: Get the dependency installation in 1 second, say goodbye to the troubles of virtual environment
TraditionPython
In development, create a virtual environment (venv
/conda
) and installing dependencies often takes several minutes, especially when dependencies are complex,pip install
The dependency analysis process is comparable to "speed".
UV
One of the core advantages is to compress this process toWithin 1 second——Whether it is installedJupyterLab
This type of medium-sized tool isscikit-learn
This type of library with C extensions,UV
All can improve installation speed through optimized caching mechanism and parallel parsing5-10 times。
Basic usage: 3 steps to start a lightweight environment
-
Create a UV environment:
uv create myenv
(Optional Python version, such as--python 3.12
) -
Activate and install dependencies:
uv activate myenv
+uv install requests rich
-
Run the script directly:
uv run my_script.py
(No need to activate the environment, automatically load dependencies)
butUV
The "fast" is not limited to this, it is more through"Run is the environment"design,
Make temporary scripts run directly without pre-configuring the environment – this is the core of the second trick.
2. The script contains: use "magic comments" to achieve independent operation, and share code with zero threshold
Have you ever repeatedly explained "You need to install X, Y, and Z libraries" when sharing scripts?
UV
ofInline dependency statementFunction, let the script come with an "environmental instruction manual". Just add it at the top of the scriptTOML format comments,UV
It can automatically read dependencies and generate temporary environments without any manual configuration.
Practical cases: Write an "out of the box" API call script
# /// script
# python = "3.12" # Specify Python version (optional)
# dependencies = ["requests>=2.28", "rich"] # Declare dependencies
# ///
import requests
from import Console
console = Console()
response = ("/posts/2")
(f"API Response: {()}")
Operation mode:uv run my_script.py
-
No need to install the dependencies in advance: UV will be automatically installed in a cached mini environment
requests
andrich
; -
Strict version control:pass
>=
or==
etc symbols specify versions to avoid "environmental inconsistency" errors; -
Cross-platform compatibility: Metadata in comments can be used by other tools (e.g.
pip-tools
) Identification to improve code universality.
This "script is environment" model is especially suitable for quickly verifying ideas, writing tutorial code, or sharing tool scripts. The receiver does not need to care about the environment configuration, just run it directly, and truly implement it"Copy and paste take effect"。
If the script does not depend on many, you don't need to add it at the beginning of the code# /// script ...
Comment, add dependencies directly on the command line.
For example, for the following code:
import pandas as pd
# Simulate data
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"Score": [85.5, 90.0, 78.3],
}
# Process data
df = (data)
df["Fraction Level"] = df["Fraction"].apply(lambda x: "A" if x >= 85 else "B")
# Save as Excel (requires openpyxl support)
df.to_csv("Score Analysis.csv", index=False)
Run the above code using the following command:uv run --with pandas my_script.py
This way, even if your environment is not pre-installedpandas
, you can also run scripts.
3. Dynamic environment isolation: Play with multiple version dependencies in the same program
When you need to test the performance of the same function under different dependencies (such asscikit-learn 1.4
vs 1.5
The traditional practice is to create/delete virtual environments frequently, and the efficiency is extremely inefficient.
UV
The ability to build a fast environment allows"Function-level environment isolation"Become possible.
Technical disassembly: How to dynamically run functions that depend on different versions?
-
Serialization functions and parameters:use
pickle
Package the objective function and its input data to ensure cross-environmental delivery; -
Generate temporary scripts: Dynamically create temporary Python files containing dependency declarations (such as specified
scikit-learn==1.4
); - Batch execution and timing: Automatically run scripts and collect results by looping through different versions.
3.0.0.1. Code framework (based onuvtrick
Bag):
from uvtrick import Env
# Define the objective function (reliable to dependencies independent of the current environment)
def run_pca():
from time import time
from import PCA
from import make_regression
X, y = make_regression(n_samples=1000, n_features=10, random_state=42)
start = time()
PCA(n_components=2).fit(X, y)
end = time()
return end - start
# Create different versions of the environment and run
for sklearn_version in ["1.4.2", "1.5.1"]:
env = Env(
f"scikit-learn=={sklearn_version}",
python="3.12",
)
result = (run_pca)
print(f"sklearn {sklearn_version} time-consuming: {result}")
The script dependency aboveuvtrick
If you don't want to install the package, use the following command to run it:
uv run --with uvtrick my_script.py
The results of running on my computer are as follows:
sklearn 1.4.2 Time consumption: 0.0019140243530273438
sklearn 1.5.1 Time consumption: 0.0008246898651123047
4. Summary
UV
The emergence of this is not only a "faster package manager", but also an innovation in development thinking.
It transforms dependency management from "the burden of environment configuration" to "the inherent attribute of code", making each script a "microenvironment" that runs independently.
Whether it is fast verification, sharing code, or complex version isolation requirements, UV can resolve pain points with amazing speed and concise design.
Now, try adding it to your next scriptUV
Comments, experience"Write and run"or useuvtrick
Explore how to play dynamic environments and unlock more possibilities.
When the tools are efficient enough, we can focus our energy on the code itself—the ultimate gift UV brings to developers.