Thanks to visit codestin.com
Credit goes to GitHub.com

Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Lib/asyncio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .events import *
from .exceptions import *
from .futures import *
from .graph import *
from .locks import *
from .protocols import *
from .runners import *
Expand All @@ -27,6 +28,7 @@
events.__all__ +
exceptions.__all__ +
futures.__all__ +
graph.__all__ +
locks.__all__ +
protocols.__all__ +
runners.__all__ +
Expand All @@ -45,3 +47,28 @@
else:
from .unix_events import * # pragma: no cover
__all__ += unix_events.__all__

def __getattr__(name: str):
import warnings

match name:
case "AbstractEventLoopPolicy":
warnings._deprecated(f"asyncio.{name}", remove=(3, 16))
return events._AbstractEventLoopPolicy
case "DefaultEventLoopPolicy":
warnings._deprecated(f"asyncio.{name}", remove=(3, 16))
if sys.platform == 'win32':
return windows_events._DefaultEventLoopPolicy
return unix_events._DefaultEventLoopPolicy
case "WindowsSelectorEventLoopPolicy":
if sys.platform == 'win32':
warnings._deprecated(f"asyncio.{name}", remove=(3, 16))
return windows_events._WindowsSelectorEventLoopPolicy
# Else fall through to the AttributeError below.
case "WindowsProactorEventLoopPolicy":
if sys.platform == 'win32':
warnings._deprecated(f"asyncio.{name}", remove=(3, 16))
return windows_events._WindowsProactorEventLoopPolicy
# Else fall through to the AttributeError below.

raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
40 changes: 37 additions & 3 deletions Lib/asyncio/__main__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import argparse
import ast
import asyncio
import asyncio.tools
import concurrent.futures
import contextvars
import inspect
Expand All @@ -10,7 +12,7 @@
import types
import warnings

from _colorize import can_colorize, ANSIColors # type: ignore[import-not-found]
from _colorize import get_theme
from _pyrepl.console import InteractiveColoredConsole

from . import futures
Expand Down Expand Up @@ -102,8 +104,9 @@ def run(self):
exec(startup_code, console.locals)

ps1 = getattr(sys, "ps1", ">>> ")
if can_colorize() and CAN_USE_PYREPL:
ps1 = f"{ANSIColors.BOLD_MAGENTA}{ps1}{ANSIColors.RESET}"
if CAN_USE_PYREPL:
theme = get_theme().syntax
ps1 = f"{theme.prompt}{ps1}{theme.reset}"
console.write(f"{ps1}import asyncio\n")

if CAN_USE_PYREPL:
Expand Down Expand Up @@ -141,6 +144,37 @@ def interrupt(self) -> None:


if __name__ == '__main__':
parser = argparse.ArgumentParser(
prog="python3 -m asyncio",
description="Interactive asyncio shell and CLI tools",
color=True,
)
subparsers = parser.add_subparsers(help="sub-commands", dest="command")
ps = subparsers.add_parser(
"ps", help="Display a table of all pending tasks in a process"
)
ps.add_argument("pid", type=int, help="Process ID to inspect")
pstree = subparsers.add_parser(
"pstree", help="Display a tree of all pending tasks in a process"
)
pstree.add_argument("pid", type=int, help="Process ID to inspect")
args = parser.parse_args()
match args.command:
case "ps":
asyncio.tools.display_awaited_by_tasks_table(args.pid)
sys.exit(0)
case "pstree":
asyncio.tools.display_awaited_by_tasks_tree(args.pid)
sys.exit(0)
case None:
pass # continue to the interactive shell
case _:
# shouldn't happen as an invalid command-line wouldn't parse
# but let's keep it for the next person adding a command
print(f"error: unhandled command {args.command}", file=sys.stderr)
parser.print_usage(file=sys.stderr)
sys.exit(1)

sys.audit("cpython.run_stdin")

if os.getenv('PYTHON_BASIC_REPL'):
Expand Down
28 changes: 12 additions & 16 deletions Lib/asyncio/base_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,24 +458,18 @@ def create_future(self):
"""Create a Future object attached to the loop."""
return futures.Future(loop=self)

def create_task(self, coro, *, name=None, context=None, **kwargs):
"""Schedule a coroutine object.
def create_task(self, coro, **kwargs):
"""Schedule or begin executing a coroutine object.

Return a task object.
"""
self._check_closed()
if self._task_factory is not None:
if context is not None:
kwargs["context"] = context

task = self._task_factory(self, coro, **kwargs)
task.set_name(name)

else:
task = tasks.Task(coro, loop=self, name=name, context=context, **kwargs)
if task._source_traceback:
del task._source_traceback[-1]
return self._task_factory(self, coro, **kwargs)

task = tasks.Task(coro, loop=self, **kwargs)
if task._source_traceback:
del task._source_traceback[-1]
try:
return task
finally:
Expand Down Expand Up @@ -841,7 +835,7 @@ def call_soon(self, callback, *args, context=None):

def _check_callback(self, callback, method):
if (coroutines.iscoroutine(callback) or
coroutines.iscoroutinefunction(callback)):
coroutines._iscoroutinefunction(callback)):
raise TypeError(
f"coroutines cannot be used with {method}()")
if not callable(callback):
Expand Down Expand Up @@ -878,7 +872,10 @@ def call_soon_threadsafe(self, callback, *args, context=None):
self._check_closed()
if self._debug:
self._check_callback(callback, 'call_soon_threadsafe')
handle = self._call_soon(callback, args, context)
handle = events._ThreadSafeHandle(callback, args, self, context)
self._ready.append(handle)
if handle._source_traceback:
del handle._source_traceback[-1]
if handle._source_traceback:
del handle._source_traceback[-1]
self._write_to_self()
Expand Down Expand Up @@ -1677,8 +1674,7 @@ async def connect_accepted_socket(
raise ValueError(
'ssl_shutdown_timeout is only meaningful with ssl')

if sock is not None:
_check_ssl_socket(sock)
_check_ssl_socket(sock)

transport, protocol = await self._create_connection_transport(
sock, protocol_factory, ssl, '', server_side=True,
Expand Down
9 changes: 9 additions & 0 deletions Lib/asyncio/coroutines.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,16 @@ def _is_debug_mode():


def iscoroutinefunction(func):
import warnings
"""Return True if func is a decorated coroutine function."""
warnings._deprecated("asyncio.iscoroutinefunction",
f"{warnings._DEPRECATED_MSG}; "
"use inspect.iscoroutinefunction() instead",
remove=(3,16))
return _iscoroutinefunction(func)


def _iscoroutinefunction(func):
return (inspect.iscoroutinefunction(func) or
getattr(func, '_is_coroutine', None) is _is_coroutine)

Expand Down
Loading
Loading