Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Microoptimize the walk() function #587

Merged
merged 1 commit into from
Jan 8, 2025
Merged
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
20 changes: 12 additions & 8 deletions pynvim/api/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,11 +241,15 @@ def decode_if_bytes(obj: T, mode: TDecodeMode = True) -> Union[T, str]:
return obj


def walk(fn: Callable[..., Any], obj: Any, *args: Any, **kwargs: Any) -> Any:
"""Recursively walk an object graph applying `fn`/`args` to objects."""
if type(obj) in [list, tuple]:
return list(walk(fn, o, *args) for o in obj)
if type(obj) is dict:
return dict((walk(fn, k, *args), walk(fn, v, *args)) for k, v in
obj.items())
return fn(obj, *args, **kwargs)
def walk(fn: Callable[[Any], Any], obj: Any) -> Any:
"""Recursively walk an object graph applying `fn` to objects."""

# Note: this function is very hot, so it is worth being careful
# about performance.
type_ = type(obj)

if type_ is list or type_ is tuple:
return [walk(fn, o) for o in obj]
if type_ is dict:
return {walk(fn, k): walk(fn, v) for k, v in obj.items()}
return fn(obj)
2 changes: 1 addition & 1 deletion pynvim/api/nvim.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ def request(self, name: str, *args: Any, **kwargs: Any) -> Any:
decode = kwargs.pop('decode', self._decode)
args = walk(self._to_nvim, args)
res = self._session.request(name, *args, **kwargs)
return walk(self._from_nvim, res, decode=decode)
return walk(partial(self._from_nvim, decode=decode), res)

def next_message(self) -> Any:
"""Block until a message(request or notification) is available.
Expand Down
2 changes: 1 addition & 1 deletion pynvim/plugin/host.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def _wrap_delayed_function(self, cls, delayed_handlers, name, sync,

def _wrap_function(self, fn, sync, decode, nvim_bind, name, *args):
if decode:
args = walk(decode_if_bytes, args, decode)
args = walk(partial(decode_if_bytes, mode=decode), args)
if nvim_bind is not None:
args.insert(0, nvim_bind)
try:
Expand Down
Loading