Skip to content

ProxyServer

The core immutable data structure representing a proxy server connection.

proxy_string.base.ProxyServer

Immutable representation of proxy server connection data and credentials.

Attributes:

Name Type Description
host str

Hostname or IP address of the proxy server.

port int

Connection port number (0..65535).

protocol ProxyServerProtocol

Proxy network protocol (HTTP, HTTPS, SOCKS4, SOCKS5).

username str | None

Optional authentication username.

password str | None

Optional authentication password.

remote_dns bool | None

Whether DNS resolution should occur on the proxy server.

unicode_host str

Unicode representation of the host (for IDN/punycode).

host_value_type HostValueType

Host classification (HOSTNAME, IPV4, or IPV6).

_host_value_type class-attribute instance-attribute

_host_value_type: HostValueType | None = field(
    default=None,
    validator=validators.optional(
        validators.instance_of(HostValueType)
    ),
    eq=False,
    hash=False,
    repr=False,
    kw_only=True,
)

_skip_validation class-attribute instance-attribute

_skip_validation: bool = field(
    default=False,
    validator=validators.instance_of(bool),
    eq=False,
    hash=False,
    repr=False,
    kw_only=True,
)

host class-attribute instance-attribute

host: str = field(
    validator=[
        validators.instance_of(str),
        validators.min_len(1),
    ],
    eq=True,
    hash=True,
    repr=True,
)

host_ip_address property

host_ip_address: IPv4Address | IPv6Address | None

Returns the IP address object if the host is an IP, otherwise None.

Returns:

Type Description
IPv4Address | IPv6Address | None

IPv4Address | IPv6Address | None: Parsed IP address object or None.

host_value_type property

host_value_type: HostValueType

Returns the classification of the host (HOSTNAME, IPV4, or IPV6).

Returns:

Name Type Description
HostValueType HostValueType

Host classification enum member.

is_authenticated property

is_authenticated: bool

Returns True if the proxy has credentials (username or password).

Returns:

Name Type Description
bool bool

True if username or password is set, False otherwise.

is_socks property

is_socks: bool

Returns True if the proxy protocol is a SOCKS protocol (SOCKS4 or SOCKS5).

Returns:

Name Type Description
bool bool

True if protocol is SOCKS4 or SOCKS5, False otherwise.

is_ssl property

is_ssl: bool

Returns True if the proxy connection uses TLS/SSL (HTTPS).

Returns:

Name Type Description
bool bool

True if protocol is HTTPS, False otherwise.

origin property

origin: str

Returns the origin URL excluding authentication credentials.

Returns:

Name Type Description
str str

Proxy origin URL without credentials.

password class-attribute instance-attribute

password: str | None = field(
    default=None,
    validator=validators.optional(
        validators.instance_of(str)
    ),
    eq=True,
    hash=True,
    repr=lambda v: "'***'" if v is not None else "None",
    kw_only=True,
)

port class-attribute instance-attribute

port: int = field(
    default=0,
    converter=int,
    validator=[validators.ge(0), validators.le(65535)],
    eq=True,
    hash=True,
    repr=True,
)

protocol class-attribute instance-attribute

protocol: ProxyServerProtocol = field(
    default=ProxyServerProtocol.HTTP,
    validator=_validate_protocol,
    eq=True,
    hash=True,
    repr=True,
    kw_only=True,
)

remote_dns class-attribute instance-attribute

remote_dns: bool | None = field(
    default=None,
    validator=validators.optional(
        validators.instance_of(bool)
    ),
    eq=True,
    hash=True,
    repr=True,
    kw_only=True,
)

unicode_host property

unicode_host: str

Returns the host decoded from IDNA Punycode to Unicode if applicable.

Returns:

Name Type Description
str str

Unicode representation of the host name.

unicode_url property

unicode_url: str

Returns the URL representation with Unicode host and credentials.

Returns:

Name Type Description
str str

Proxy URL with decoded Unicode hostname.

url property

url: str

Returns the full URL representation including credentials.

Returns:

Name Type Description
str str

Absolute proxy URL.

username class-attribute instance-attribute

username: str | None = field(
    default=None,
    validator=validators.optional(
        validators.instance_of(str)
    ),
    eq=True,
    hash=True,
    repr=lambda v: repr(v) if v is not None else "None",
    kw_only=True,
)

__attrs_post_init__

__attrs_post_init__() -> None

Sets default port and resolves default remote_dns flag for the protocol.

Source code in src/proxy_string/base.py
def __attrs_post_init__(self) -> None:
    """Sets default port and resolves default remote_dns flag for the protocol."""
    if self._skip_validation:
        if self._host_value_type is None:
            raise ProxyConfigurationError(
                "The 'host_value_type' parameter must be specified "
                "when validation is skipped."
            )
        object.__setattr__(self, "_skip_validation", False)
        return

    scheme = url_tools.get_scheme(self.protocol, self.remote_dns)
    if scheme in ("http", "https") and self.remote_dns is True:
        raise ProtocolConstraintError(
            f"{scheme.upper()} protocol does not support remote DNS resolution.",
            protocol=scheme,
            host=self.host,
        )
    elif scheme in ("socks4a", "socks5h") and self.remote_dns is False:
        raise ProtocolConstraintError(
            f"Conflicting configuration: scheme '{scheme}' requires "
            "remote DNS resolution, but 'remote_dns' is set to False.",
            protocol=scheme,
            host=self.host,
        )

    parsed = parse_url(
        url_tools.build_url(
            scheme, self.host, self.port, self.username, self.password
        )
    )

    remote_dns = (
        self.remote_dns if parsed["remote_dns"] is None else parsed["remote_dns"]
    )

    object.__setattr__(self, "protocol", parsed["protocol"])
    object.__setattr__(self, "host", parsed["host"])
    object.__setattr__(self, "port", parsed["port"])
    object.__setattr__(self, "username", parsed["username"])
    object.__setattr__(self, "password", parsed["password"])
    object.__setattr__(self, "remote_dns", remote_dns)
    object.__setattr__(self, "_host_value_type", parsed["host_value_type"])
    object.__setattr__(self, "_skip_validation", False)

__str__

__str__() -> str

Returns the URL representation of the proxy server.

Source code in src/proxy_string/base.py
def __str__(self) -> str:
    """Returns the URL representation of the proxy server."""
    return self.to_url()

from_dict classmethod

from_dict(input_dict: Mapping[str, Any]) -> Self

Creates a ProxyServer instance from a dictionary of parameters.

Parameters:

Name Type Description Default
input_dict Mapping[str, Any]

Dictionary containing proxy configuration keys ('host', 'port', 'protocol' or 'scheme', 'username', 'password', 'remote_dns').

required

Returns:

Name Type Description
ProxyServer Self

A new ProxyServer instance.

Raises:

Type Description
TypeError

If input_dict is not a Mapping.

ProxyConfigurationError

If 'host' is missing or empty.

Source code in src/proxy_string/base.py
@classmethod
def from_dict(cls, input_dict: Mapping[str, Any]) -> Self:
    """Creates a ProxyServer instance from a dictionary of parameters.

    Args:
        input_dict: Dictionary containing proxy configuration keys
            ('host', 'port', 'protocol' or 'scheme', 'username',
            'password', 'remote_dns').

    Returns:
        ProxyServer: A new ProxyServer instance.

    Raises:
        TypeError: If input_dict is not a Mapping.
        ProxyConfigurationError: If 'host' is missing or empty.
    """
    if not isinstance(input_dict, Mapping):
        raise TypeError("Input data must be a dictionary or mapping!")

    if "host" not in input_dict or not input_dict["host"]:
        raise ProxyConfigurationError(
            "Input dictionary must contain a non-empty 'host' key."
        )

    port = input_dict.get("port")
    kwargs: dict[str, Any] = {
        "host": input_dict["host"],
        # first try to get "scheme" since scheme can be "socks4a" or "socks5h"
        "protocol": input_dict.get(
            "scheme", input_dict.get("protocol", ProxyServerProtocol.HTTP)
        ),
        "username": input_dict.get("username"),
        "password": input_dict.get("password"),
        "remote_dns": input_dict.get("remote_dns"),
    }
    if port is not None:
        kwargs["port"] = port

    return cls(**kwargs)

from_file classmethod

from_file(
    input_file: str | Path,
    *,
    string_format: ProxyStringFormat | None = None,
    protocol: ProxyServerProtocol | None = None,
    encoding: str = "utf-8",
    encoding_errors: str = "strict",
    ignore_invalid: bool = False,
) -> Generator[Self, None, None]

Yields ProxyServer instances by reading proxy strings from a file.

Parameters:

Name Type Description Default
input_file str | Path

Path to the proxy text file.

required
string_format ProxyStringFormat | None

Optional explicit ProxyStringFormat for rows. Recommended when usernames or passwords are numeric to avoid port ambiguity in 4-part colon-delimited strings.

None
protocol ProxyServerProtocol | None

Optional protocol override for all rows.

None
encoding str

Text encoding of the file (defaults to 'utf-8').

'utf-8'
encoding_errors str

Text codec error handling mode passed to open() (defaults to 'strict').

'strict'
ignore_invalid bool

If True, rows that cannot be parsed are skipped. If False (default), raises InvalidProxyStringError or ValueError.

False

Yields:

Name Type Description
ProxyServer Self

Parsed proxy server instances.

Raises:

Type Description
InvalidProxyStringError

If a row cannot be parsed and ignore_invalid is False.

Source code in src/proxy_string/base.py
@classmethod
def from_file(  # noqa: PLR0913
    cls,
    input_file: str | Path,
    *,
    string_format: ProxyStringFormat | None = None,
    protocol: ProxyServerProtocol | None = None,
    encoding: str = "utf-8",
    encoding_errors: str = "strict",
    ignore_invalid: bool = False,
) -> Generator[Self, None, None]:
    """Yields ProxyServer instances by reading proxy strings from a file.

    Args:
        input_file: Path to the proxy text file.
        string_format: Optional explicit ProxyStringFormat for rows.
            Recommended when usernames or passwords are numeric to avoid
            port ambiguity in 4-part colon-delimited strings.
        protocol: Optional protocol override for all rows.
        encoding: Text encoding of the file (defaults to 'utf-8').
        encoding_errors: Text codec error handling mode passed to open()
            (defaults to 'strict').
        ignore_invalid: If True, rows that cannot be parsed are skipped.
            If False (default), raises InvalidProxyStringError or ValueError.

    Yields:
        ProxyServer: Parsed proxy server instances.

    Raises:
        InvalidProxyStringError: If a row cannot be parsed and
            ignore_invalid is False.
    """
    with open(input_file, encoding=encoding, errors=encoding_errors) as infile:
        for row in infile:
            line = row.strip()
            if not line or line.startswith("#"):
                continue
            try:
                yield cls.from_string(
                    line, string_format=string_format, protocol=protocol
                )
            except (ProxyStringError, ValueError):
                if not ignore_invalid:
                    raise

from_file_async async classmethod

from_file_async(
    input_file: str | Path,
    *,
    string_format: ProxyStringFormat | None = None,
    protocol: ProxyServerProtocol | None = None,
    encoding: str = "utf-8",
    encoding_errors: str = "strict",
    ignore_invalid: bool = False,
) -> AsyncGenerator[Self, None]

Asynchronously yields ProxyServer instances by reading a file.

Parameters:

Name Type Description Default
input_file str | Path

Path to the proxy text file.

required
string_format ProxyStringFormat | None

Optional explicit ProxyStringFormat for rows. Recommended when usernames or passwords are numeric to avoid port ambiguity in 4-part colon-delimited strings.

None
protocol ProxyServerProtocol | None

Optional protocol override for all rows.

None
encoding str

Text encoding of the file (defaults to 'utf-8').

'utf-8'
encoding_errors str

Text codec error handling mode passed to open() (defaults to 'strict').

'strict'
ignore_invalid bool

If True, rows that cannot be parsed are skipped. If False (default), raises InvalidProxyStringError or ValueError.

False

Yields:

Name Type Description
ProxyServer AsyncGenerator[Self, None]

Parsed proxy server instances.

Raises:

Type Description
InvalidProxyStringError

If a row cannot be parsed and ignore_invalid is False.

Source code in src/proxy_string/base.py
@classmethod
async def from_file_async(  # noqa: PLR0913
    cls,
    input_file: str | Path,
    *,
    string_format: ProxyStringFormat | None = None,
    protocol: ProxyServerProtocol | None = None,
    encoding: str = "utf-8",
    encoding_errors: str = "strict",
    ignore_invalid: bool = False,
) -> AsyncGenerator[Self, None]:
    """Asynchronously yields ProxyServer instances by reading a file.

    Args:
        input_file: Path to the proxy text file.
        string_format: Optional explicit ProxyStringFormat for rows.
            Recommended when usernames or passwords are numeric to avoid
            port ambiguity in 4-part colon-delimited strings.
        protocol: Optional protocol override for all rows.
        encoding: Text encoding of the file (defaults to 'utf-8').
        encoding_errors: Text codec error handling mode passed to open()
            (defaults to 'strict').
        ignore_invalid: If True, rows that cannot be parsed are skipped.
            If False (default), raises InvalidProxyStringError or ValueError.

    Yields:
        ProxyServer: Parsed proxy server instances.

    Raises:
        InvalidProxyStringError: If a row cannot be parsed and
            ignore_invalid is False.
    """
    async with aiofiles.open(
        input_file, encoding=encoding, errors=encoding_errors
    ) as infile:
        async for row in infile:
            line = row.strip()
            if not line or line.startswith("#"):
                continue
            try:
                yield cls.from_string(
                    line, string_format=string_format, protocol=protocol
                )
            except (ProxyStringError, ValueError):
                if not ignore_invalid:
                    raise

from_json classmethod

from_json(input_json: str) -> Self

Creates a ProxyServer instance from a JSON-formatted string.

Parameters:

Name Type Description Default
input_json str

JSON string representing proxy parameters.

required

Returns:

Name Type Description
ProxyServer Self

A new ProxyServer instance.

Raises:

Type Description
JSONDecodeError

If input_json is not valid JSON.

Source code in src/proxy_string/base.py
@classmethod
def from_json(cls, input_json: str) -> Self:
    """Creates a ProxyServer instance from a JSON-formatted string.

    Args:
        input_json: JSON string representing proxy parameters.

    Returns:
        ProxyServer: A new ProxyServer instance.

    Raises:
        json.JSONDecodeError: If input_json is not valid JSON.
    """
    input_dict = json.loads(input_json)
    return cls.from_dict(input_dict)

from_string classmethod

from_string(
    proxy_string: str,
    *,
    string_format: ProxyStringFormat | None = None,
    protocol: ProxyServerProtocol | None = None,
) -> Self

Creates a ProxyServer instance by parsing a formatted proxy string.

Parameters:

Name Type Description Default
proxy_string str

Formatted proxy string (e.g. 'host:port', 'user:pass@host:port').

required
string_format ProxyStringFormat | None

Optional explicit ProxyStringFormat to match against. Recommended when usernames or passwords are numeric to avoid port ambiguity in 4-part colon-delimited strings.

None
protocol ProxyServerProtocol | None

Optional protocol override (defaults to parsed protocol or HTTP).

None

Returns:

Name Type Description
ProxyServer Self

A new ProxyServer instance.

Raises:

Type Description
InvalidProxyStringError

If the string does not match the expected format.

Source code in src/proxy_string/base.py
@classmethod
def from_string(
    cls,
    proxy_string: str,
    *,
    string_format: ProxyStringFormat | None = None,
    protocol: ProxyServerProtocol | None = None,
) -> Self:
    """Creates a ProxyServer instance by parsing a formatted proxy string.

    Args:
        proxy_string: Formatted proxy string (e.g. 'host:port',
            'user:pass@host:port').
        string_format: Optional explicit ProxyStringFormat to match against.
            Recommended when usernames or passwords are numeric to avoid
            port ambiguity in 4-part colon-delimited strings.
        protocol: Optional protocol override (defaults to parsed protocol or HTTP).

    Returns:
        ProxyServer: A new ProxyServer instance.

    Raises:
        InvalidProxyStringError: If the string does not match the expected format.
    """
    proxy_string = proxy_string.strip()
    if string_format:
        parsed_proxy = dict(parse_proxy_string(proxy_string, string_format))
        if protocol:
            parsed_proxy["protocol"] = protocol
            parsed_proxy.pop("skip_validation", None)
        return cls(**parsed_proxy)

    possible_formats = detect_possible_formats(proxy_string)

    for _, parsed_proxy in possible_formats:
        parsed = dict(parsed_proxy)
        if protocol:
            parsed["protocol"] = protocol
            parsed.pop("skip_validation", None)

        with suppress(ProxyStringError, ValueError):
            return cls(**parsed)

    raise InvalidProxyStringError(
        f"Unable to parse the proxy string: '{proxy_string}'!",
        proxy_string=proxy_string,
    )

from_url classmethod

from_url(url: str) -> Self

Creates a ProxyServer instance by parsing a proxy URL.

Parameters:

Name Type Description Default
url str

A complete proxy URL (e.g. 'http://user:pass@proxy.com:8080').

required

Returns:

Name Type Description
ProxyServer Self

A new ProxyServer instance.

Raises:

Type Description
InvalidProxyURLError

If the URL format, scheme, or host is invalid.

Source code in src/proxy_string/base.py
@classmethod
def from_url(cls, url: str) -> Self:
    """Creates a ProxyServer instance by parsing a proxy URL.

    Args:
        url: A complete proxy URL (e.g. 'http://user:pass@proxy.com:8080').

    Returns:
        ProxyServer: A new ProxyServer instance.

    Raises:
        InvalidProxyURLError: If the URL format, scheme, or host is invalid.
    """
    return cls(**parse_url(url))

prepare_for

prepare_for(
    package_name: Literal["urllib", "requests"],
) -> dict[str, str]
prepare_for(
    package_name: Literal["playwright"],
) -> dict[str, str | None]
prepare_for(
    package_name: Literal[
        "urllib3",
        "httpx",
        "httpx2",
        "aiohttp",
        "pycurl",
        "curl_cffi",
    ],
) -> str
prepare_for(
    package_name: SupportedPackage | str,
) -> dict[str, Any] | str
prepare_for(
    package_name: SupportedPackage | str,
) -> dict[str, Any] | str

Prepares proxy configuration for third-party libraries.

Parameters:

Name Type Description Default
package_name SupportedPackage | str

Target library name ('urllib', 'requests', 'urllib3', 'httpx', 'httpx2', 'aiohttp', 'playwright', 'pycurl', or 'curl_cffi').

required

Returns:

Type Description
dict[str, Any] | str

dict[str, Any] | str: Library-specific proxy configuration structure.

Raises:

Type Description
UnsupportedPackageError

If the package is not supported.

ProtocolNotSupportedError

If the protocol is incompatible.

Source code in src/proxy_string/base.py
def prepare_for(self, package_name: SupportedPackage | str) -> dict[str, Any] | str:
    """Prepares proxy configuration for third-party libraries.

    Args:
        package_name: Target library name ('urllib', 'requests', 'urllib3',
            'httpx', 'httpx2', 'aiohttp', 'playwright', 'pycurl', or 'curl_cffi').

    Returns:
        dict[str, Any] | str: Library-specific proxy configuration structure.

    Raises:
        UnsupportedPackageError: If the package is not supported.
        ProtocolNotSupportedError: If the protocol is incompatible.
    """
    match package_name.strip().lower():
        case "urllib":
            _check_for_protocol_support(self, "urllib", ("http", "https"))
            url = self.to_url(socks_ext=True)
            return {"http": url, "https": url}
        case "requests":
            url = self.to_url(socks_ext=True)
            return {"http": url, "https": url}
        case "urllib3" | "httpx" | "httpx2" | "aiohttp" | "pycurl" | "curl_cffi":
            return self.to_url(socks_ext=True)
        case "playwright":
            _check_for_protocol_support(
                self, "playwright", ("http", "https", "socks5"), socks_ext=False
            )
            return {
                "server": self.to_url(socks_ext=False, exclude_credentials=True),
                "username": self.username,
                "password": self.password,
            }
        case _:
            raise UnsupportedPackageError(
                f"Package '{package_name}' is not supported.",
                package_name=package_name,
            )

to_dict

to_dict() -> dict[str, Any]

Serializes proxy server attributes into a dictionary.

Returns:

Name Type Description
dict dict[str, Any]

Dictionary with host, port, protocol, username, password, remote_dns.

Source code in src/proxy_string/base.py
def to_dict(self) -> dict[str, Any]:
    """Serializes proxy server attributes into a dictionary.

    Returns:
        dict: Dictionary with host, port, protocol, username, password, remote_dns.
    """
    return {
        "host": self.host,
        "port": self.port,
        "protocol": self.protocol,
        "username": self.username,
        "password": self.password,
        "remote_dns": self.remote_dns,
    }

to_json

to_json() -> str

Serializes proxy server attributes into a JSON string.

Returns:

Name Type Description
str str

JSON representation of the proxy server.

Source code in src/proxy_string/base.py
def to_json(self) -> str:
    """Serializes proxy server attributes into a JSON string.

    Returns:
        str: JSON representation of the proxy server.
    """
    return json.dumps(self.to_dict())

to_string

to_string(
    string_format: ProxyStringFormat | None = None,
) -> str

Formats the proxy server into a specified or auto-selected string format.

Parameters:

Name Type Description Default
string_format ProxyStringFormat | None

Format template from ProxyStringFormat. If None, defaults to HOST_PORT_USER_PASS when credentials are present, otherwise HOST_PORT.

None

Returns:

Name Type Description
str str

Formatted proxy string.

Source code in src/proxy_string/base.py
def to_string(
    self,
    string_format: ProxyStringFormat | None = None,
) -> str:
    """Formats the proxy server into a specified or auto-selected string format.

    Args:
        string_format: Format template from ProxyStringFormat. If None,
            defaults to HOST_PORT_USER_PASS when credentials are present,
            otherwise HOST_PORT.

    Returns:
        str: Formatted proxy string.
    """
    if string_format is ProxyStringFormat.URL:
        return self.to_url()

    if string_format is None:
        string_format = (
            ProxyStringFormat.HOST_PORT_USER_PASS
            if self.username is not None or self.password is not None
            else ProxyStringFormat.HOST_PORT
        )

    format_str = PROXY_STRING_FORMATS[string_format]
    return format_str.format(
        host=self.host,
        port=self.port,
        username=self.username or "",
        password=self.password or "",
    )

to_url

to_url(
    socks_ext: bool = True,
    exclude_credentials: bool = False,
) -> str

Serializes proxy server to URL string.

Parameters:

Name Type Description Default
socks_ext bool

Whether to use extended SOCKS schemes ('socks4a', 'socks5h').

True
exclude_credentials bool

If True, omits username and password from the URL.

False

Returns:

Name Type Description
str str

Proxy server URL.

Source code in src/proxy_string/base.py
def to_url(self, socks_ext: bool = True, exclude_credentials: bool = False) -> str:
    """Serializes proxy server to URL string.

    Args:
        socks_ext: Whether to use extended SOCKS schemes ('socks4a', 'socks5h').
        exclude_credentials: If True, omits username and password from the URL.

    Returns:
        str: Proxy server URL.
    """
    scheme = url_tools.get_scheme(self.protocol, self.remote_dns, socks_ext)

    if exclude_credentials:
        return url_tools.build_url(scheme, self.host, self.port)
    return url_tools.build_url(
        scheme, self.host, self.port, self.username, self.password
    )

with_creds

with_creds(
    username: str | None, password: str | None
) -> Self

Returns a copy of the proxy with modified credentials.

Parameters:

Name Type Description Default
username str | None

The new username credential.

required
password str | None

The new password credential.

required

Returns:

Name Type Description
Self Self

A new proxy server instance.

Source code in src/proxy_string/base.py
def with_creds(self, username: str | None, password: str | None) -> Self:
    """Returns a copy of the proxy with modified credentials.

    Args:
        username: The new username credential.
        password: The new password credential.

    Returns:
        Self: A new proxy server instance.
    """
    return evolve(self, username=username, password=password)

with_host

with_host(host: str) -> Self

Returns a copy of the proxy with a modified host.

Parameters:

Name Type Description Default
host str

The new host name or IP address.

required

Returns:

Name Type Description
Self Self

A new proxy server instance.

Source code in src/proxy_string/base.py
def with_host(self, host: str) -> Self:
    """Returns a copy of the proxy with a modified host.

    Args:
        host: The new host name or IP address.

    Returns:
        Self: A new proxy server instance.
    """
    return evolve(self, host=host)

with_password

with_password(password: str | None) -> Self

Returns a copy of the proxy with a modified password.

Parameters:

Name Type Description Default
password str | None

The new password credential.

required

Returns:

Name Type Description
Self Self

A new proxy server instance.

Source code in src/proxy_string/base.py
def with_password(self, password: str | None) -> Self:
    """Returns a copy of the proxy with a modified password.

    Args:
        password: The new password credential.

    Returns:
        Self: A new proxy server instance.
    """
    return evolve(self, password=password)

with_port

with_port(port: int) -> Self

Returns a copy of the proxy with a modified port.

Parameters:

Name Type Description Default
port int

The new port number.

required

Returns:

Name Type Description
Self Self

A new proxy server instance.

Source code in src/proxy_string/base.py
def with_port(self, port: int) -> Self:
    """Returns a copy of the proxy with a modified port.

    Args:
        port: The new port number.

    Returns:
        Self: A new proxy server instance.
    """
    return evolve(self, port=port)

with_protocol

with_protocol(protocol: ProxyServerProtocol | str) -> Self

Returns a copy of the proxy with a modified protocol.

Parameters:

Name Type Description Default
protocol ProxyServerProtocol | str

The new proxy protocol enum member or protocol name string.

required

Returns:

Name Type Description
Self Self

A new proxy server instance.

Source code in src/proxy_string/base.py
def with_protocol(self, protocol: ProxyServerProtocol | str) -> Self:
    """Returns a copy of the proxy with a modified protocol.

    Args:
        protocol: The new proxy protocol enum member or protocol name string.

    Returns:
        Self: A new proxy server instance.
    """
    return evolve(self, protocol=protocol)

with_remote_dns

with_remote_dns(remote_dns: bool | None) -> Self

Returns a copy of the proxy with a modified remote_dns flag.

Parameters:

Name Type Description Default
remote_dns bool | None

Whether DNS resolution should occur on the proxy.

required

Returns:

Name Type Description
Self Self

A new proxy server instance.

Source code in src/proxy_string/base.py
def with_remote_dns(self, remote_dns: bool | None) -> Self:
    """Returns a copy of the proxy with a modified remote_dns flag.

    Args:
        remote_dns: Whether DNS resolution should occur on the proxy.

    Returns:
        Self: A new proxy server instance.
    """
    return evolve(self, remote_dns=remote_dns)

with_username

with_username(username: str | None) -> Self

Returns a copy of the proxy with a modified username.

Parameters:

Name Type Description Default
username str | None

The new username credential.

required

Returns:

Name Type Description
Self Self

A new proxy server instance.

Source code in src/proxy_string/base.py
def with_username(self, username: str | None) -> Self:
    """Returns a copy of the proxy with a modified username.

    Args:
        username: The new username credential.

    Returns:
        Self: A new proxy server instance.
    """
    return evolve(self, username=username)

proxy_string.base.SupportedPackage module-attribute

SupportedPackage = Literal[
    "aiohttp",
    "curl_cffi",
    "httpx",
    "httpx2",
    "playwright",
    "pycurl",
    "requests",
    "urllib",
    "urllib3",
]