Skip to content

pip.conf

The following models help to parse and generate the ~/.config/pip/pip.conf file.

This config can also exist globally at /etc/pip.conf.

Dependencies

  • pydantic
  • tomli_w

Code

from typing import List, Dict, Any, Optional
from pydantic import BaseModel, Field

import tomli_w

class PipGlobalConfig(BaseModel):
    index_url: Optional[str] = Field(None, alias="index-url")
    extra_index_url: Optional[str] = Field(None, alias="extra-index-url")
    trusted_host: Optional[str] = Field(None, alias="trusted-host")
    timeout: Optional[int] = None


class PipInstallConfig(BaseModel):
    no_cache_dir: Optional[bool] = None


class PipListConfig(BaseModel):
    format: Optional[str] = None


class PipConfig(BaseModel):
    global_: Optional[PipGlobalConfig] = Field(None, alias="global")
    install: Optional[PipInstallConfig] = None
    list: Optional[PipListConfig] = None

    def to_dict(self):
        return self.model_dump(by_alias=True, exclude_none=True)

    def __str__(self):
        return tomli_w.dumps(self.to_dict())

Example

pip_config = PipConfig(**{
    "global": {
        "index-url": "http://foo.example.com",
        "extra-index-url": "http://bar.example.com",
        "trusted-host": "foo.example.com",
    }
})

print(pip_config)

Which outputs

[global]
index-url = "http://foo.example.com"
extra-index-url = "http://bar.example.com"
trusted-host = "foo.example.com"