Protocol Structural Typing Adapter
Define a typing.Protocol so any object with the right shape plugs in without inheritance, and verify conformance with runtime isinstance.
Code
from typing import Protocol, runtime_checkable
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
class DatabaseConn:
def close(self) -> None:
print('db: draining connections')
class FileHandle:
def close(self) -> None:
print('file: flushing buffer')
class NotCloseable:
def shutdown(self) -> None: # 名字不同,结构不匹配
...
def release(resource: Closeable) -> None:
resource.close()
if __name__ == '__main__':
for obj in (DatabaseConn(), FileHandle()):
# isinstance 对 runtime_checkable 协议只检查方法是否存在
print(type(obj).__name__, 'is closeable:', isinstance(obj, Closeable))
release(obj)
print('NotCloseable is closeable:', isinstance(NotCloseable(), Closeable))Output
Captured from a sandboxed run of this snippet in the build pipeline.
DatabaseConn is closeable: True
db: draining connections
FileHandle is closeable: True
file: flushing buffer
NotCloseable is closeable: FalseHow the snippet works
The snippet is organized around the classes Closeable, DatabaseConn and FileHandle and the functions close, shutdown and release.
Repetition is confined to for obj in (DatabaseConn(), FileHandle()) — the rest of the file is straight-line.
Using it
The primary signature is def close(self) -> None
The demo output is labeled (db: draining connections, file: flushing buffer, NotCloseable is closeable:), so every printed line maps back to its originating operation.
Key statements
def release(resource: Closeable) -> None:
resource.close()
def close(self) -> None:
print('db: draining connections')
def close(self) -> None:
print('file: flushing buffer')
Interactive Tools for This Topic
FAQ
- What does Protocol Structural Typing Adapter print when run?
- Running the file directly is enough — expect labeled output lines such as `db: draining connections`, `file: flushing buffer`, `NotCloseable is closeable:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.