Skip to content

Commit

Permalink
Improve async to sync logic
Browse files Browse the repository at this point in the history
  • Loading branch information
Danstiv committed Jan 4, 2025
1 parent c983d71 commit 5ea4c76
Showing 1 changed file with 43 additions and 15 deletions.
58 changes: 43 additions & 15 deletions pyrogram/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,31 +83,59 @@ async def coro_wrapper():
else:
return async_to_sync_gen(coroutine, main_loop, False)

async_to_sync_wrap._orig = function

setattr(obj, name, async_to_sync_wrap)


def wrap(source):
for name in dir(source):
method = getattr(source, name)
def wrap_entity(entity):
for name in dir(entity):
method = getattr(entity, name)

if not name.startswith("_"):
if inspect.iscoroutinefunction(method) or inspect.isasyncgenfunction(method):
async_to_sync(source, name)
async_to_sync(entity, name)

def unwrap_entity(entity):
for name in dir(entity):
method = getattr(entity, name)

if not name.startswith("_"):
if hasattr(method, "_orig"):
setattr(entity, name, method._orig)

# Wrap all Client's relevant methods
wrap(Methods)

# Wrap types' bound methods
for class_name in dir(types):
cls = getattr(types, class_name)
def wrap():
# Wrap all Client's relevant methods
wrap_entity(Methods)

if inspect.isclass(cls):
wrap(cls)
# Wrap types' bound methods
for class_name in dir(types):
cls = getattr(types, class_name)

if inspect.isclass(cls):
wrap_entity(cls)

# Special case for idle and compose, because they are not inside Methods
async_to_sync(idle_module, "idle")

async_to_sync(compose_module, "compose")

# Special case for idle and compose, because they are not inside Methods
async_to_sync(idle_module, "idle")
idle = getattr(idle_module, "idle")

async_to_sync(compose_module, "compose")
def unwrap():
unwrap_entity(Methods)

for class_name in dir(types):
cls = getattr(types, class_name)

if inspect.isclass(cls):
unwrap_entity(cls)

idle_module.idle = idle_module.idle._orig
compose_module.compose = compose_module.compose._orig


wrap()

idle = getattr(idle_module, "idle")
compose = getattr(compose_module, "compose")

0 comments on commit 5ea4c76

Please sign in to comment.