Skip to content

Commit

Permalink
Preparatory work
Browse files Browse the repository at this point in the history
Small tweaks to make yapf work better
  • Loading branch information
njsmith committed Aug 3, 2017
1 parent 7494353 commit fac7c3b
Show file tree
Hide file tree
Showing 7 changed files with 101 additions and 68 deletions.
20 changes: 12 additions & 8 deletions trio/_core/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@
"ResourceBusyError",
]

# Exceptions often get printed as module.Classname. We pretend these are in
# the trio namespace (where they'll eventually end up) so that users get
# better messages.
def pretend_module_is_trio(cls):
cls.__module__ = "trio"
return cls

@pretend_module_is_trio
class TrioInternalError(Exception):
"""Raised by :func:`run` if we encounter a bug in trio, or (possibly) a
misuse of one of the low-level :mod:`trio.hazmat` APIs.
Expand All @@ -20,28 +28,25 @@ class TrioInternalError(Exception):
"""
pass

TrioInternalError.__module__ = "trio"


@pretend_module_is_trio
class RunFinishedError(RuntimeError):
"""Raised by ``run_in_trio_thread`` and similar functions if the
corresponding call to :func:`trio.run` has already finished.
"""
pass

RunFinishedError.__module__ = "trio"


@pretend_module_is_trio
class WouldBlock(Exception):
"""Raised by ``X_nowait`` functions if ``X`` would block.
"""
pass

WouldBlock.__module__ = "trio"


@pretend_module_is_trio
class Cancelled(BaseException):
"""Raised by blocking calls if the surrounding scope has been cancelled.
Expand Down Expand Up @@ -72,9 +77,8 @@ class Cancelled(BaseException):
"""
_scope = None

Cancelled.__module__ = "trio"


@pretend_module_is_trio
class ResourceBusyError(Exception):
"""Raised when a task attempts to use a resource that some other task is
already using, and this would lead to bugs and nonsense.
Expand Down
12 changes: 7 additions & 5 deletions trio/_core/_io_windows.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ def __init__(self):
# except that wakeup socket is mapped to None
self._socket_waiters = {"read": {}, "write": {}}
self._main_thread_waker = WakeupSocketpair()
self._socket_waiters["read"][self._main_thread_waker.wakeup_sock] = None
wakeup_sock = self._main_thread_waker.wakeup_sock
self._socket_waiters["read"][wakeup_sock] = None

# This is necessary to allow control-C to interrupt select().
# https://github.com/python-trio/trio/issues/42
Expand Down Expand Up @@ -237,11 +238,12 @@ def do_select():
else:
# dispatch on lpCompletionKey
queue = self._completion_key_queues[entry.lpCompletionKey]
overlapped = int(ffi.cast("uintptr_t", entry.lpOverlapped))
transferred = entry.dwNumberOfBytesTransferred
info = CompletionKeyEventInfo(
lpOverlapped=
int(ffi.cast("uintptr_t", entry.lpOverlapped)),
dwNumberOfBytesTransferred=
entry.dwNumberOfBytesTransferred)
lpOverlapped=overlapped,
dwNumberOfBytesTransferred=transferred,
)
queue.put_nowait(info)

def _iocp_thread_fn(self):
Expand Down
4 changes: 3 additions & 1 deletion trio/_core/_ki.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@

from . import _hazmat

__all__ = ["enable_ki_protection", "disable_ki_protection", "currently_ki_protected"]
__all__ = [
"enable_ki_protection", "disable_ki_protection", "currently_ki_protected",
]

# In ordinary single-threaded Python code, when you hit control-C, it raises
# an exception and automatically does all the regular unwinding stuff.
Expand Down
27 changes: 16 additions & 11 deletions trio/_core/tests/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,17 +460,22 @@ async def main():
("before_run",),
("schedule", tasks["t1"]),
("schedule", tasks["t2"]),
{("before", tasks["t1"]),
("after", tasks["t1"]),
("before", tasks["t2"]),
("after", tasks["t2"])},
{("schedule", tasks["t1"]),
("before", tasks["t1"]),
("after", tasks["t1"]),
("schedule", tasks["t2"]),
("before", tasks["t2"]),
("after", tasks["t2"])},
("after_run",)]
{
("before", tasks["t1"]),
("after", tasks["t1"]),
("before", tasks["t2"]),
("after", tasks["t2"])
},
{
("schedule", tasks["t1"]),
("before", tasks["t1"]),
("after", tasks["t1"]),
("schedule", tasks["t2"]),
("before", tasks["t2"]),
("after", tasks["t2"])
},
("after_run",),
] # yapf: disable
print(list(r.filter_tasks(tasks.values())))
check_sequence_matches(list(r.filter_tasks(tasks.values())), expected)

Expand Down
51 changes: 31 additions & 20 deletions trio/socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,30 +22,35 @@ def _reexport(name):


# Usage:
#
# async with _try_sync():
# return sync_call_that_might_fail_with_exception()
# # we only get here if the sync call in fact did fail with an exception
# # that passed the blocking_exc_check
# # we only get here if the sync call in fact did fail with a
# # BlockingIOError
# return await do_it_properly_with_a_check_point()

def _is_blocking_io_error(exc):
return isinstance(exc, BlockingIOError)

#
class _try_sync:
def __init__(self, blocking_exc_check=_is_blocking_io_error):
self._blocking_exc_check = blocking_exc_check
def __init__(self, blocking_exc_override=None):
self._blocking_exc_override = blocking_exc_override

def _is_blocking_io_error(self, exc):
if self._blocking_exc_override is None:
return isinstance(exc, BlockingIOError)
else:
return self._blocking_exc_override(exc)

async def __aenter__(self):
await _core.yield_if_cancelled()

async def __aexit__(self, etype, value, tb):
if value is not None and self._blocking_exc_check(value):
# discard the exception and fall through to the code below the
if value is not None and self._is_blocking_io_error(value):
# Discard the exception and fall through to the code below the
# block
return True
else:
await _core.yield_briefly_no_cancel()
# Let the return or exception propagate
return False


################################################################
Expand Down Expand Up @@ -163,8 +168,15 @@ def set_custom_socket_factory(socket_factory):
# getaddrinfo and friends
################################################################

def _add_to_all(obj):
__all__.append(obj.__name__)
return obj


_NUMERIC_ONLY = _stdlib_socket.AI_NUMERICHOST | _stdlib_socket.AI_NUMERICSERV


@_add_to_all
async def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
"""Look up a numeric address given a name.
Expand Down Expand Up @@ -215,9 +227,8 @@ def numeric_only_failure(exc):
_stdlib_socket.getaddrinfo, host, port, family, type, proto, flags,
cancellable=True)

__all__.append("getaddrinfo")


@_add_to_all
async def getnameinfo(sockaddr, flags):
"""Look up a name given a numeric address.
Expand All @@ -235,9 +246,9 @@ async def getnameinfo(sockaddr, flags):
return await _run_in_worker_thread(
_stdlib_socket.getnameinfo, sockaddr, flags, cancellable=True)

__all__.append("getnameinfo")


@_add_to_all
async def getprotobyname(name):
"""Look up a protocol number by name. (Rarely used.)
Expand All @@ -247,7 +258,6 @@ async def getprotobyname(name):
return await _run_in_worker_thread(
_stdlib_socket.getprotobyname, name, cancellable=True)

__all__.append("getprotobyname")

# obsolete gethostbyname etc. intentionally omitted

Expand All @@ -256,43 +266,44 @@ async def getprotobyname(name):
# Socket "constructors"
################################################################

@_add_to_all
def from_stdlib_socket(sock):
"""Convert a standard library :func:`socket.socket` object into a trio
socket object.
"""
return _SocketType(sock)
__all__.append("from_stdlib_socket")


@_wraps(_stdlib_socket.fromfd, assigned=(), updated=())
@_add_to_all
def fromfd(*args, **kwargs):
"""Like :func:`socket.fromfd`, but returns a trio socket object.
"""
return from_stdlib_socket(_stdlib_socket.fromfd(*args, **kwargs))
__all__.append("fromfd")


if hasattr(_stdlib_socket, "fromshare"):
@_wraps(_stdlib_socket.fromshare, assigned=(), updated=())
@_add_to_all
def fromshare(*args, **kwargs):
return from_stdlib_socket(_stdlib_socket.fromshare(*args, **kwargs))
__all__.append("fromshare")


@_wraps(_stdlib_socket.socketpair, assigned=(), updated=())
@_add_to_all
def socketpair(*args, **kwargs):
"""Like :func:`socket.socketpair`, but returns a pair of trio socket
objects.
"""
left, right = _stdlib_socket.socketpair(*args, **kwargs)
return (from_stdlib_socket(left), from_stdlib_socket(right))
__all__.append("socketpair")


@_wraps(_stdlib_socket.socket, assigned=(), updated=())
@_add_to_all
def socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
"""Create a new trio socket, like :func:`socket.socket`.
Expand All @@ -306,13 +317,13 @@ def socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
return sf.socket(family, type, proto)
stdlib_socket = _stdlib_socket.socket(family, type, proto, fileno)
return from_stdlib_socket(stdlib_socket)
__all__.append("socket")


################################################################
# Type checking
################################################################

@_add_to_all
def is_trio_socket(obj):
"""Check whether the given object is a trio socket.
Expand All @@ -325,7 +336,6 @@ def is_trio_socket(obj):
return True
return isinstance(obj, _SocketType)

__all__.append("is_trio_socket")

################################################################
# _SocketType
Expand All @@ -349,6 +359,7 @@ def is_trio_socket(obj):
def _real_type(type_num):
return type_num & _SOCK_TYPE_MASK

@_add_to_all
class _SocketType:
def __init__(self, sock):
if type(sock) is not _stdlib_socket.socket:
Expand Down
4 changes: 3 additions & 1 deletion trio/ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,14 +174,16 @@ def _reexport(name):
globals()[name] = value
__all__.append(name)


# Intentionally not re-exported:
# SSLContext
for _name in [
"SSLError", "SSLZeroReturnError", "SSLSyscallError", "SSLEOFError",
"CertificateError", "create_default_context", "match_hostname",
"cert_time_to_seconds", "DER_cert_to_PEM_cert", "PEM_cert_to_DER_cert",
"get_default_verify_paths", "Purpose", "enum_certificates",
"enum_crls", "SSLSession", "VerifyMode", "VerifyFlags", "Options",
"AlertDescription", "SSLErrorNumber",
# Intentionally not re-exported: SSLContext
]:
_reexport(_name)

Expand Down
Loading

0 comments on commit fac7c3b

Please sign in to comment.