Location>code7788 >text

New gameplay of unlocking UV tools: Practical tips to make Python scripts run more efficiently

Popularity:666 ℃/2025-04-27 12:21:06

AsPythonDevelopers, 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, aUVTools are quietly emerging. It is not only known for its rapid installation and dependence, but also reconstructed through a series of innovative designs.PythonThe script's running logic.

This article mainly introducesUVThree 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

TraditionPythonIn development, create a virtual environment (venv/conda) and installing dependencies often takes several minutes, especially when dependencies are complex,pip installThe dependency analysis process is comparable to "speed".

UVOne of the core advantages is to compress this process toWithin 1 second——Whether it is installedJupyterLabThis type of medium-sized tool isscikit-learnThis type of library with C extensions,UVAll can improve installation speed through optimized caching mechanism and parallel parsing5-10 times

Basic usage: 3 steps to start a lightweight environment

  1. Create a UV environmentuv create myenv(Optional Python version, such as--python 3.12
  2. Activate and install dependenciesuv activate myenv + uv install requests rich
  3. Run the script directlyuv run my_script.pyNo need to activate the environment, automatically load dependencies)

butUVThe "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?

UVofInline dependency statementFunction, let the script come with an "environmental instruction manual". Just add it at the top of the scriptTOML format commentsUVIt 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 environmentrequestsandrich
  • 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.5The traditional practice is to create/delete virtual environments frequently, and the efficiency is extremely inefficient.

UVThe 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?

  1. Serialization functions and parameters:usepicklePackage the objective function and its input data to ensure cross-environmental delivery;
  2. Generate temporary scripts: Dynamically create temporary Python files containing dependency declarations (such as specifiedscikit-learn==1.4);
  3. Batch execution and timing: Automatically run scripts and collect results by looping through different versions.

3.0.0.1. Code framework (based onuvtrickBag):

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 aboveuvtrickIf 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

UVThe 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 scriptUVComments, experience"Write and run"or useuvtrickExplore 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.