Python ssl - wrap sockets with SSLContext and create_default_context
Answer: ssl.create_default_context() returns a new SSLContext object with default settings. This module provides some more Pythonic support for SSL on top of OpenSSL. Use wrap_socket on an existing Python socket.
Examples
import socket, ssl
hostname = "example.com"
context = ssl.create_default_context()
with socket.create_connection((hostname, 443), timeout=5) as raw:
with context.wrap_socket(raw, server_hostname=hostname) as tls:
print(tls.version(), tls.selected_alpn_protocol())
tls.sendall(b"HEAD / HTTP/1.1\r\nHost: example.com\r\n\r\n")
print(tls.recv(1024))
Rules
- The installed version of OpenSSL may cause variations in behavior.
See also
Claims
- id: C1 claim: create_default_context returns an SSLContext with default settings. source: S1 evidence: "Return a new SSLContext object with default settings"
- id: C2 claim: The module provides Pythonic support for SSL. source: S2 evidence: "This module provides some more Pythonic support for SSL"
- id: C3 claim: OpenSSL versions can change TLS behavior. source: S1 evidence: "The installed version of OpenSSL may also cause variations in behavior"
Sources
- [S1] ssl - TLS/SSL wrapper for socket objects. Python docs. https://docs.python.org/3/library/ssl.html . License: PSF-2.0. Accessed 2026-11-18.
- [S2] Lib/ssl.py. python/cpython (GitHub). https://github.com/python/cpython/blob/main/Lib/ssl.py . License: PSF-2.0. Accessed 2026-11-18.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, ssl - TLS/SSL wrapper for socket objects; python/cpython (GitHub), Lib/ssl.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, ssl - TLS/SSL wrapper for socket objects; python/cpython (GitHub), Lib/ssl.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.
Cite this
iinventedlight. 2026. "Python ssl - wrap sockets with SSLContext and create_default_context." iinventedlight Library, iil:note:h8y5p5jp, version of 2026-11-18. https://iinventedlight.com/library/notes/python-ssl/. License: CC-BY-4.0.
@misc{iil_note_h8y5p5jp,
author = {{iinventedlight}},
title = {{Python ssl - wrap sockets with SSLContext and create\_default\_context}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-18},
url = {https://iinventedlight.com/library/notes/python-ssl/},
note = {Permanent ID iil:note:h8y5p5jp. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).
For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-ssl.md.