Skip to content

Commit

Permalink
Enable pydocstyle rules in ruff and fix errors (#438)
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobtomlinson authored Jul 4, 2024
1 parent 04469f3 commit f6fdffc
Show file tree
Hide file tree
Showing 16 changed files with 199 additions and 225 deletions.
111 changes: 56 additions & 55 deletions kr8s/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
# SPDX-FileCopyrightText: Copyright (c) 2023-2024, Kr8s Developers (See LICENSE for list)
# SPDX-License-Identifier: BSD 3-Clause License
"""
This module contains `kr8s`, a simple, extensible Python client library for Kubernetes.
At the top level, `kr8s` provides a synchronous API that wraps the asynchronous API provided by `kr8s.asyncio`.
Both APIs are functionally identical with the same objects, method signatures and return values.
"""
from functools import partial, update_wrapper
from typing import Optional, Union
from typing import Dict, List, Optional, Union

from . import asyncio, objects, portforward
from ._api import ALL
Expand Down Expand Up @@ -47,39 +53,37 @@ class Api(_AsyncApi):
__doc__ = _AsyncApi.__doc__


def get(*args, **kwargs):
def get(
kind: str,
*names: List[str],
namespace: Optional[str] = None,
label_selector: Optional[Union[str, Dict]] = None,
field_selector: Optional[Union[str, Dict]] = None,
as_object: Optional[object] = None,
allow_unknown_type: bool = True,
api=None,
**kwargs,
):
"""Get a resource by name.
Parameters
----------
kind : str
The kind of resource to get
*names : List[str]
The names of the resources to get
namespace : str, optional
The namespace to get the resource from
label_selector : Union[str, Dict], optional
The label selector to filter the resources by
field_selector : Union[str, Dict], optional
The field selector to filter the resources by
as_object : object, optional
The object to populate with the resource data
api : Api, optional
The api to use to get the resource
Returns
-------
object
Args:
kind: The kind of resource to get
*names: The names of the resources to get
namespace: The namespace to get the resource from
label_selector: The label selector to filter the resources by
field_selector: The field selector to filter the resources by
as_object: The object to populate with the resource data
allow_unknown_type: Whether to allow unknown types
api: The api to use to get the resource
**kwargs: Additional arguments to pass to the API
Returns:
The populated object
Raises
------
ValueError
If the resource is not found
Examples
--------
Raises:
ValueError: If the resource is not found
Examples:
>>> import kr8s
>>> # All of these are equivalent
>>> ings = kr8s.get("ing") # Short name
Expand All @@ -90,7 +94,18 @@ def get(*args, **kwargs):
>>> ings = kr8s.get("ingress.v1.networking.k8s.io") # Full with explicit version
>>> ings = kr8s.get("ingress.networking.k8s.io/v1") # Full with explicit version alt.
"""
return _run_sync(partial(_get, _asyncio=False))(*args, **kwargs)
return _run_sync(_get)(
kind,
*names,
namespace=namespace,
label_selector=label_selector,
field_selector=field_selector,
as_object=as_object,
allow_unknown_type=allow_unknown_type,
api=api,
_asyncio=False,
**kwargs,
)


def api(
Expand All @@ -104,27 +119,17 @@ def api(
If a kr8s object already exists with the same arguments in this thread, it will be returned.
Parameters
----------
url : str, optional
The URL of the Kubernetes API server
kubeconfig : str, optional
The path to a kubeconfig file to use
serviceaccount : str, optional
The path of a service account to use
namespace : str, optional
The namespace to use
context : str, optional
The context to use
Returns
-------
Api
The API object
Args:
url: The URL of the Kubernetes API server
kubeconfig: The path to a kubeconfig file to use
serviceaccount: The path of a service account to use
namespace: The namespace to use
context: The context to use
Examples
--------
Returns:
The API object
Examples:
>>> import kr8s
>>> api = kr8s.api() # Uses the default kubeconfig
>>> print(api.version()) # Get the Kubernetes version
Expand All @@ -144,14 +149,10 @@ def api(
def whoami():
"""Get the current user's identity.
Returns
-------
str
Returns:
The user's identity
Examples
--------
Examples:
>>> import kr8s
>>> print(kr8s.whoami())
"""
Expand Down
63 changes: 20 additions & 43 deletions kr8s/_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,7 @@ async def open_websocket(
async def version(self) -> dict:
"""Get the Kubernetes version information from the API.
Returns
-------
dict
Returns:
The Kubernetes version information.
"""
Expand Down Expand Up @@ -325,23 +323,14 @@ async def lookup_kind(self, kind) -> Tuple[str, bool]:
Check whether a resource kind exists on the remote server.
Parameters
----------
kind : str
The kind of resource to lookup.
Returns
-------
str
The kind of resource.
bool
Whether the resource is namespaced
Args:
kind: The kind of resource to lookup.
Raises
------
Returns:
The kind of resource and whether the resource is namespaced
ValueError
If the kind is not found.
Raises:
ValueError: If the kind is not found.
"""
return await self.async_lookup_kind(kind)

Expand Down Expand Up @@ -416,31 +405,19 @@ async def get(
allow_unknown_type: bool = True,
**kwargs,
) -> Union[APIObject, List[APIObject]]:
"""
Get Kubernetes resources.
Parameters
----------
kind : str, type
The kind of resource to get.
*names : List[str], optional
The names of specific resources to get.
namespace : str, optional
The namespace to get the resource from.
label_selector : Union[str, Dict], optional
The label selector to filter the resources by.
field_selector : Union[str, Dict], optional
The field selector to filter the resources by.
as_object : object, optional
The object to return the resources as.
allow_unknown_type:
Automatically create a class for the resource if none exists, default True.
**kwargs
Additional keyword arguments to pass to the API call.
Returns
-------
List[object]
"""Get Kubernetes resources.
Args:
kind: The kind of resource to get.
*names: The names of specific resources to get.
namespace: The namespace to get the resource from.
label_selector: The label selector to filter the resources by.
field_selector: The field selector to filter the resources by.
as_object: The object to return the resources as.
allow_unknown_type: Automatically create a class for the resource if none exists, default True.
**kwargs: Additional keyword arguments to pass to the API call.
Returns:
The resources.
"""
return await self.async_get(
Expand Down
1 change: 0 additions & 1 deletion kr8s/_async_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ def run_sync(
Returns:
Callable: A sync function that executes the coroutine via the :class`Portal`.
"""

if inspect.isasyncgenfunction(coro):

@wraps(coro)
Expand Down
68 changes: 22 additions & 46 deletions kr8s/_data_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,12 @@ def list_dict_unpack(
) -> Dict:
"""Convert a list of dictionaries to a single dictionary.
Parameters
----------
input_list : List[Dict]
The list of dictionaries to convert to a single dictionary.
key : str, optional
The key to use for the new dictionary's keys. Defaults to "key".
value : str, optional
The key to use for the new dictionary's values. Defaults to "value".
Returns
-------
Dict
Args:
input_list: The list of dictionaries to convert to a single dictionary.
key: The key to use for the new dictionary's keys. Defaults to "key".
value: The key to use for the new dictionary's values. Defaults to "value".
Returns:
A dictionary with the keys and values from the input list.
"""
return {i[key]: i[value] for i in input_list}
Expand All @@ -31,18 +25,12 @@ def dict_list_pack(
) -> List[Dict]:
"""Convert a dictionary to a list of dictionaries.
Parameters
----------
input_dict : Dict
The dictionary to convert to a list of dictionaries.
key : str, optional
The key to use for the input dictionary's keys. Defaults to "key".
value : str, optional
The key to use for the input dictionary's values. Defaults to "value".
Returns
-------
List[Dict]
Args:
input_dict: The dictionary to convert to a list of dictionaries.
key: The key to use for the input dictionary's keys. Defaults to "key".
value: The key to use for the input dictionary's values. Defaults to "value".
Returns:
A list of dictionaries with the keys and values from the input dictionary.
"""
return [{key: k, value: v} for k, v in input_dict.items()]
Expand All @@ -51,16 +39,11 @@ def dict_list_pack(
def dot_to_nested_dict(dot_notated_key: str, value: Any) -> Dict:
"""Convert a dot notated key to a nested dictionary.
Parameters
----------
dot_notated_key : str
The dot notated key to convert to a nested dictionary.
value : Any
The value to assign to the innermost key.
Args:
dot_notated_key: The dot notated key to convert to a nested dictionary.
value: The value to assign to the innermost key.
Returns
-------
Dict
Returns:
A nested dictionary with the innermost key being the value of the
dot notated key.
"""
Expand All @@ -77,14 +60,10 @@ def dot_to_nested_dict(dot_notated_key: str, value: Any) -> Dict:
def dict_to_selector(selector_dict: Dict) -> str:
"""Convert a dictionary to a Kubernetes selector.
Parameters
----------
selector_dict : Dict
The dictionary to convert to a Kubernetes selector.
Args:
selector_dict: The dictionary to convert to a Kubernetes selector.
Returns
-------
str
Returns:
A Kubernetes selector string.
"""
return ",".join(f"{k}={v}" for k, v in selector_dict.items())
Expand All @@ -94,14 +73,11 @@ def xdict(*in_dict, **kwargs):
"""Dictionary constructor that ignores None values.
Args:
in_dict : Dict
A dict to convert. Only one is allowed.
**kwargs
Keyword arguments to be converted to a dict.
in_dict: A dict to convert. Only one is allowed.
**kwargs: Keyword arguments to be converted to a dict.
Returns:
Dict
A dict with None values removed.
A dict with None values removed.
Raises:
ValueError
Expand Down
9 changes: 3 additions & 6 deletions kr8s/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,9 @@ class ExecError(Exception):
class ServerError(Exception):
"""Error from the Kubernetes API server.
Attributes
----------
status : str
The Status object from the Kubernetes API server
response : httpx.Response
The httpx response object
Attributes:
status: The Status object from the Kubernetes API server
response: The httpx response object
"""

def __init__(
Expand Down
2 changes: 1 addition & 1 deletion kr8s/_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,6 @@ async def get(
**kwargs,
) -> APIObject:
"""Get a Kubernetes resource by name or via selectors."""

if api is None:
if cls._asyncio:
api = await kr8s.asyncio.api()
Expand Down Expand Up @@ -1684,6 +1683,7 @@ def object_from_spec(
Args:
spec: A Kubernetes resource spec.
api: An optional API instance to use.
allow_unknown_type: Whether to allow unknown resource types.
_asyncio: Whether to use asyncio or not.
Expand Down
Loading

0 comments on commit f6fdffc

Please sign in to comment.