Python Glossary Русский

all Python 3socketfunction

socket.setdefaulttimeout()

timeouts

Sets the default timeout for every socket created after the call, process-wide.

Syntax

socket.setdefaulttimeout(timeout)  # число секунд или None

The setting is global: it also affects sockets inside libraries (urllib, http.client, smtplib), so library code never touches it and passes timeout= or calls settimeout() on its own socket instead. Existing sockets are not changed. 0 makes every new socket non-blocking (BlockingIOError instead of waiting), None restores waiting with no limit. An expired timeout raises TimeoutError; since 3.10 socket.timeout is merely another name for it. Name resolution (getaddrinfo) is not bounded by this timeout.

Examples

import socket
with socket.socket() as old:
    socket.setdefaulttimeout(0.5)
    with socket.socket() as new:
        print(old.gettimeout(), new.gettimeout())  # → None 0.5
socket.setdefaulttimeout(None)
print(socket.getdefaulttimeout())  # → None
# Python 3.10+
import socket
socket.setdefaulttimeout(0.1)
a, b = socket.socketpair()
with a, b:
    try:
        b.recv(1024)
    except TimeoutError as e:
        print(e)  # → timed out
print(socket.timeout is TimeoutError)  # → True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy