Skip to content

Commit 8a30c8e

Browse files
authored
clib.Session: Add type hints and improve docstrings of the Session create/destroy methods (#3515)
1 parent 871d106 commit 8a30c8e

File tree

1 file changed

+43
-47
lines changed

1 file changed

+43
-47
lines changed

pygmt/clib/session.py

Lines changed: 43 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import pathlib
1212
import sys
1313
import warnings
14-
from collections.abc import Generator, Sequence
14+
from collections.abc import Callable, Generator, Sequence
1515
from typing import Literal
1616

1717
import numpy as np
@@ -268,7 +268,9 @@ def get_enum(self, name: str) -> int:
268268
raise GMTCLibError(f"Constant '{name}' doesn't exist in libgmt.")
269269
return value
270270

271-
def get_libgmt_func(self, name, argtypes=None, restype=None):
271+
def get_libgmt_func(
272+
self, name: str, argtypes: list | None = None, restype=None
273+
) -> Callable:
272274
"""
273275
Get a ctypes function from the libgmt shared library.
274276
@@ -278,14 +280,14 @@ def get_libgmt_func(self, name, argtypes=None, restype=None):
278280
279281
Parameters
280282
----------
281-
name : str
283+
name
282284
The name of the GMT API function.
283-
argtypes : list
284-
List of ctypes types used to convert the Python input arguments for
285-
the API function.
285+
argtypes
286+
List of ctypes types used to convert the Python input arguments for the API
287+
function.
286288
restype : ctypes type
287-
The ctypes type used to convert the input returned by the function
288-
into a Python type.
289+
The ctypes type used to convert the input returned by the function into a
290+
Python type.
289291
290292
Returns
291293
-------
@@ -312,43 +314,42 @@ def get_libgmt_func(self, name, argtypes=None, restype=None):
312314
function.restype = restype
313315
return function
314316

315-
def create(self, name):
317+
def create(self, name: str):
316318
"""
317319
Create a new GMT C API session.
318320
319-
This is required before most other methods of
320-
:class:`pygmt.clib.Session` can be called.
321+
This is required before most other methods of :class:`pygmt.clib.Session` can be
322+
called.
321323
322324
.. warning::
323325
324-
Usage of :class:`pygmt.clib.Session` as a context manager in a
325-
``with`` block is preferred over calling
326-
:meth:`pygmt.clib.Session.create` and
326+
Usage of :class:`pygmt.clib.Session` as a context manager in a ``with``
327+
block is preferred over calling :meth:`pygmt.clib.Session.create` and
327328
:meth:`pygmt.clib.Session.destroy` manually.
328329
329-
Calls ``GMT_Create_Session`` and generates a new ``GMTAPI_CTRL``
330-
struct, which is a :class:`ctypes.c_void_p` pointer. Sets the
331-
``session_pointer`` attribute to this pointer.
330+
Calls ``GMT_Create_Session`` and generates a new ``GMTAPI_CTRL`` struct, which
331+
is a :class:`ctypes.c_void_p` pointer. Sets the ``session_pointer`` attribute to
332+
this pointer.
332333
333334
Remember to terminate the current session using
334335
:meth:`pygmt.clib.Session.destroy` before creating a new one.
335336
336337
Parameters
337338
----------
338-
name : str
339+
name
339340
A name for this session. Doesn't really affect the outcome.
340341
"""
341342
try:
342-
# Won't raise an exception if there is a currently open session
343+
# Won't raise an exception if there is a currently open session.
343344
_ = self.session_pointer
344-
# In this case, fail to create a new session until the old one is
345-
# destroyed
346-
raise GMTCLibError(
345+
# In this case, fail to create a new session until the old one is destroyed.
346+
msg = (
347347
"Failed to create a GMT API session: There is a currently open session."
348348
" Must destroy it first."
349349
)
350-
# If the exception is raised, this means that there is no open session
351-
# and we're free to create a new one.
350+
raise GMTCLibError(msg)
351+
# If the exception is raised, this means that there is no open session and we're
352+
# free to create a new one.
352353
except GMTCLibNoSessionError:
353354
pass
354355

@@ -358,9 +359,9 @@ def create(self, name):
358359
restype=ctp.c_void_p,
359360
)
360361

361-
# Capture the output printed by GMT into this list. Will use it later
362-
# to generate error messages for the exceptions raised by API calls.
363-
self._error_log = []
362+
# Capture the output printed by GMT into this list. Will use it later to
363+
# generate error messages for the exceptions raised by API calls.
364+
self._error_log: list[str] = []
364365

365366
@ctp.CFUNCTYPE(ctp.c_int, ctp.c_void_p, ctp.c_char_p)
366367
def print_func(file_pointer, message): # noqa: ARG001
@@ -382,24 +383,22 @@ def print_func(file_pointer, message): # noqa: ARG001
382383
print(message, file=sys.stderr, flush=True) # noqa: T201
383384
return 0
384385

385-
# Need to store a copy of the function because ctypes doesn't and it
386-
# will be garbage collected otherwise
386+
# Need to store a copy of the function because ctypes doesn't and it will be
387+
# garbage collected otherwise
387388
self._print_callback = print_func
388389

389390
padding = self["GMT_PAD_DEFAULT"]
390391
session_type = self["GMT_SESSION_EXTERNAL"]
391-
392392
session = c_create_session(name.encode(), padding, session_type, print_func)
393393

394394
if session is None:
395-
raise GMTCLibError(
396-
f"Failed to create a GMT API session:\n{self._error_message}"
397-
)
395+
msg = f"Failed to create a GMT API session:\n{self._error_message}"
396+
raise GMTCLibError(msg)
398397

399398
self.session_pointer = session
400399

401400
@property
402-
def _error_message(self):
401+
def _error_message(self) -> str:
403402
"""
404403
A string with all error messages emitted by the C API.
405404
@@ -416,19 +415,17 @@ def destroy(self):
416415
417416
.. warning::
418417
419-
Usage of :class:`pygmt.clib.Session` as a context manager in a
420-
``with`` block is preferred over calling
421-
:meth:`pygmt.clib.Session.create` and
418+
Usage of :class:`pygmt.clib.Session` as a context manager in a ``with``
419+
block is preferred over calling :meth:`pygmt.clib.Session.create` and
422420
:meth:`pygmt.clib.Session.destroy` manually.
423421
424-
Calls ``GMT_Destroy_Session`` to terminate and free the memory of a
425-
registered ``GMTAPI_CTRL`` session (the pointer for this struct is
426-
stored in the ``session_pointer`` attribute).
422+
Calls ``GMT_Destroy_Session`` to terminate and free the memory of a registered
423+
``GMTAPI_CTRL`` session (the pointer for this struct is stored in the
424+
``session_pointer`` attribute).
427425
428-
Always use this method after you are done using a C API session. The
429-
session needs to be destroyed before creating a new one. Otherwise,
430-
some of the configuration files might be left behind and can influence
431-
subsequent API calls.
426+
Always use this method after you are done using a C API session. The session
427+
needs to be destroyed before creating a new one. Otherwise, some of the
428+
configuration files might be left behind and can influence subsequent API calls.
432429
433430
Sets the ``session_pointer`` attribute to ``None``.
434431
"""
@@ -438,9 +435,8 @@ def destroy(self):
438435

439436
status = c_destroy_session(self.session_pointer)
440437
if status:
441-
raise GMTCLibError(
442-
f"Failed to destroy GMT API session:\n{self._error_message}"
443-
)
438+
msg = f"Failed to destroy GMT API session:\n{self._error_message}"
439+
raise GMTCLibError(msg)
444440

445441
self.session_pointer = None
446442

0 commit comments

Comments
 (0)