Skip to content

Commit

Permalink
refactor: remove the use of forward references #558
Browse files Browse the repository at this point in the history
With PEP-563 (Postponed evaluation of annotations), we can have a more
clean syntax of writing type hints, not using 'forward references' to
names that have not been defined yet in the form of string literals.

Note that Python 3.7+ (the minimum python version that is currently
supported by pynvim) supports PEP-563.
  • Loading branch information
wookayin authored Jan 14, 2024
1 parent c4197f1 commit 5f989df
Show file tree
Hide file tree
Showing 6 changed files with 33 additions and 22 deletions.
10 changes: 7 additions & 3 deletions pynvim/api/buffer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
"""API for working with a Nvim Buffer."""

from __future__ import annotations

from typing import (Any, Iterator, List, Optional, TYPE_CHECKING, Tuple, Union, cast,
overload)

Expand Down Expand Up @@ -44,7 +47,7 @@ class Buffer(Remote):
_api_prefix = "nvim_buf_"
_session: "Nvim"

def __init__(self, session: "Nvim", code_data: Tuple[int, Any]):
def __init__(self, session: Nvim, code_data: Tuple[int, Any]):
"""Initialize from Nvim and code_data immutable object."""
super().__init__(session, code_data)

Expand Down Expand Up @@ -150,7 +153,7 @@ def mark(self, name: str) -> Tuple[int, int]:
"""Return (row, col) tuple for a named mark."""
return cast(Tuple[int, int], tuple(self.request('nvim_buf_get_mark', name)))

def range(self, start: int, end: int) -> "Range":
def range(self, start: int, end: int) -> Range:
"""Return a `Range` object, which represents part of the Buffer."""
return Range(self, start, end)

Expand Down Expand Up @@ -245,7 +248,8 @@ def number(self) -> int:
return self.handle


class Range(object):
class Range:

def __init__(self, buffer: Buffer, start: int, end: int):
self._buffer = buffer
self.start = start - 1
Expand Down
5 changes: 2 additions & 3 deletions pynvim/api/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,7 @@ def request(self, name: str, *args: Any, **kwargs: Any) -> Any:
return self._session.request(name, self, *args, **kwargs)


class RemoteApi(object):

class RemoteApi:
"""Wrapper to allow api methods to be called like python methods."""

def __init__(self, obj: IRemote, api_prefix: str):
Expand All @@ -106,7 +105,7 @@ def transform_keyerror(exc: E) -> Union[E, KeyError]:
return exc


class RemoteMap(object):
class RemoteMap:
"""Represents a string->object map stored in Nvim.
This is the dict counterpart to the `RemoteSequence` class, but it is used
Expand Down
25 changes: 12 additions & 13 deletions pynvim/api/nvim.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Main Nvim interface."""

from __future__ import annotations

import asyncio
import os
import sys
Expand Down Expand Up @@ -56,8 +58,7 @@
"""


class Nvim(object):

class Nvim:
"""Class that represents a remote Nvim instance.
This class is main entry point to Nvim remote API, it is a wrapper
Expand All @@ -81,7 +82,7 @@ class Nvim(object):
"""

@classmethod
def from_session(cls, session: 'Session') -> 'Nvim':
def from_session(cls, session: Session) -> Nvim:
"""Create a new Nvim instance for a Session instance.
This method must be called to create the first Nvim instance, since it
Expand All @@ -102,14 +103,14 @@ def from_session(cls, session: 'Session') -> 'Nvim':
return cls(session, channel_id, metadata, types)

@classmethod
def from_nvim(cls, nvim: 'Nvim') -> 'Nvim':
def from_nvim(cls, nvim: Nvim) -> Nvim:
"""Create a new Nvim instance from an existing instance."""
return cls(nvim._session, nvim.channel_id, nvim.metadata,
nvim.types, nvim._decode, nvim._err_cb)

def __init__(
self,
session: 'Session',
session: Session,
channel_id: int,
metadata: Dict[str, Any],
types: Dict[int, Any],
Expand Down Expand Up @@ -168,7 +169,7 @@ def _to_nvim(self, obj: Any) -> Any:
return ExtType(*obj.code_data)
return obj

def _get_lua_private(self) -> 'LuaFuncs':
def _get_lua_private(self) -> LuaFuncs:
if not getattr(self._session, "_has_lua", False):
self.exec_lua(lua_module, self.channel_id)
self._session._has_lua = True # type: ignore[attr-defined]
Expand Down Expand Up @@ -269,7 +270,7 @@ def close(self) -> None:
"""Close the nvim session and release its resources."""
self._session.close()

def __enter__(self) -> 'Nvim':
def __enter__(self) -> Nvim:
"""Enter nvim session as a context manager."""
return self

Expand All @@ -280,7 +281,7 @@ def __exit__(self, *exc_info: Any) -> None:
"""
self.close()

def with_decode(self, decode: Literal[True] = True) -> 'Nvim':
def with_decode(self, decode: Literal[True] = True) -> Nvim:
"""Initialize a new Nvim instance."""
return Nvim(self._session, self.channel_id,
self.metadata, self.types, decode, self._err_cb)
Expand Down Expand Up @@ -575,8 +576,7 @@ def tabpage(self, tabpage: Union[Tabpage, int]) -> None:
return self._session.request('nvim_set_current_tabpage', tabpage)


class Funcs(object):

class Funcs:
"""Helper class for functional vimscript interface."""

def __init__(self, nvim: Nvim):
Expand All @@ -586,15 +586,14 @@ def __getattr__(self, name: str) -> Callable[..., Any]:
return partial(self._nvim.call, name)


class LuaFuncs(object):

class LuaFuncs:
"""Wrapper to allow lua functions to be called like python methods."""

def __init__(self, nvim: Nvim, name: str = ""):
self._nvim = nvim
self.name = name

def __getattr__(self, name: str) -> 'LuaFuncs':
def __getattr__(self, name: str) -> LuaFuncs:
"""Return wrapper to named api method."""
prefix = self.name + "." if self.name else ""
return LuaFuncs(self._nvim, prefix + name)
Expand Down
6 changes: 5 additions & 1 deletion pynvim/api/tabpage.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
"""API for working with Nvim tabpages."""

from __future__ import annotations

from typing import Any, TYPE_CHECKING, Tuple

from pynvim.api.common import Remote, RemoteSequence
from pynvim.api.window import Window

if TYPE_CHECKING:
from pynvim.api.nvim import Nvim

Expand All @@ -15,7 +19,7 @@ class Tabpage(Remote):

_api_prefix = "nvim_tabpage_"

def __init__(self, session: 'Nvim', code_data: Tuple[int, Any]):
def __init__(self, session: Nvim, code_data: Tuple[int, Any]):
"""Initialize from session and code_data immutable object.
The `code_data` contains serialization information required for
Expand Down
5 changes: 4 additions & 1 deletion pynvim/api/window.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
"""API for working with Nvim windows."""

from __future__ import annotations

from typing import TYPE_CHECKING, Tuple, cast

from pynvim.api.buffer import Buffer
Expand Down Expand Up @@ -63,7 +66,7 @@ def col(self) -> int:
return self.request('nvim_win_get_position')[1]

@property
def tabpage(self) -> 'Tabpage':
def tabpage(self) -> Tabpage:
"""Get the `Tabpage` that contains the window."""
return self.request('nvim_win_get_tabpage')

Expand Down
4 changes: 3 additions & 1 deletion pynvim/msgpack_rpc/event_loop/asyncio.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Event loop implementation that uses the `asyncio` standard module."""

from __future__ import annotations

import asyncio
import logging
import os
Expand Down Expand Up @@ -91,7 +93,7 @@ class AsyncioEventLoop(BaseEventLoop):
_signals: List[Signals]
_data_buffer: Deque[bytes]
if os.name != 'nt':
_child_watcher: Optional['asyncio.AbstractChildWatcher']
_child_watcher: Optional[asyncio.AbstractChildWatcher]

def __init__(self,
transport_type: TTransportType,
Expand Down

0 comments on commit 5f989df

Please sign in to comment.