Skip to content

Commit

Permalink
docs: Start using Darglint (#1387)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoGorelli authored Nov 16, 2024
1 parent 251444c commit bbf3a5f
Show file tree
Hide file tree
Showing 13 changed files with 235 additions and 121 deletions.
22 changes: 22 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,28 @@ repos:
files: \.(py|rst|md)$
args: [--ignore-words-list=ser]
exclude: ^docs/api-completeness.md$
- repo: https://github.com/pycqa/flake8
rev: '7.1.1' # todo: remove once https://github.com/astral-sh/ruff/issues/458 is addressed
hooks:
- id: flake8
additional_dependencies: [darglint==1.8.1, Flake8-pyproject]
entry: flake8 --select DAR --ignore DAR402,DAR401
exclude: |
(?x)^(
tests/.*|
# TODO: gradually enable
narwhals/series\.py$|
# TODO: gradually enable
narwhals/dataframe\.py$|
# TODO: gradually enable
narwhals/dependencies\.py$|
# some false positives in this one
narwhals/translate\.py$|
# some false positives in this one
narwhals/stable/v1/__init__\.py$|
# private, so less urgent to document too well
narwhals/_.*
)$
- repo: local
hooks:
- id: check-api-reference
Expand Down
6 changes: 5 additions & 1 deletion narwhals/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,11 @@ def __repr__(self) -> str:
return f"{class_name}({dict(self)})"

def to_schema(self) -> OrderedDict[str, DType | type[DType]]:
"""Return Struct dtype as a schema dict."""
"""Return Struct dtype as a schema dict.
Returns:
Mapping from column name to dtype.
"""
return OrderedDict(self)


Expand Down
15 changes: 11 additions & 4 deletions narwhals/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ def alias(self, name: str) -> Self:
def pipe(self, function: Callable[[Any], Self], *args: Any, **kwargs: Any) -> Self:
"""Pipe function call.
Arguments:
function: Function to apply.
args: Positional arguments to pass to function.
kwargs: Keyword arguments to pass to function.
Returns:
A new expression.
Expand Down Expand Up @@ -1075,6 +1080,9 @@ def diff(self) -> Self:
def shift(self, n: int) -> Self:
"""Shift values by `n` positions.
Arguments:
n: Number of positions to shift values by.
Returns:
A new expression.
Expand Down Expand Up @@ -1310,9 +1318,7 @@ def is_between(
Arguments:
lower_bound: Lower bound value.
upper_bound: Upper bound value.
closed: Define which sides of the interval are closed (inclusive).
Returns:
Expand Down Expand Up @@ -1427,6 +1433,9 @@ def is_in(self, other: Any) -> Self:
def filter(self, *predicates: Any) -> Self:
"""Filters elements based on a condition, returning a new expression.
Arguments:
predicates: Conditions to filter by (which get ANDed together).
Returns:
A new expression.
Expand Down Expand Up @@ -1607,9 +1616,7 @@ def fill_null(
Arguments:
value: Value used to fill null values.
strategy: Strategy used to fill null values.
limit: Number of consecutive null values to fill when using the 'forward' or 'backward' strategy.
Returns:
Expand Down
23 changes: 15 additions & 8 deletions narwhals/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,11 @@ def concat(
Arguments:
items: DataFrames, LazyFrames to concatenate.
how: {'vertical', 'horizontal'}
* vertical: Stacks Series from DataFrames vertically and fills with `null`
if the lengths don't match.
* horizontal: Stacks Series from DataFrames horizontally and fills with `null`
if the lengths don't match.
- vertical: Stacks Series from DataFrames vertically and fills with `null`
if the lengths don't match.
- horizontal: Stacks Series from DataFrames horizontally and fills with `null`
if the lengths don't match.
Returns:
A new DataFrame, Lazyframe resulting from the concatenation.
Expand Down Expand Up @@ -534,6 +533,8 @@ def _get_sys_info() -> dict[str, str]:
Copied from sklearn
Returns:
Dictionary with system info.
"""
python = sys.version.replace("\n", " ")

Expand All @@ -556,6 +557,8 @@ def _get_deps_info() -> dict[str, str]:
This function and show_versions were copied from sklearn and adapted
Returns:
Mapping from dependency to version.
"""
deps = (
"pandas",
Expand Down Expand Up @@ -607,9 +610,13 @@ def get_level(
) -> Literal["full", "interchange"]:
"""Level of support Narwhals has for current object.
This can be one of:
Arguments:
obj: Dataframe or Series.
Returns:
This can be one of:
- 'full': full Narwhals API support
- 'metadata': only metadata operations are supported (`df.schema`)
- 'full': full Narwhals API support
- 'metadata': only metadata operations are supported (`df.schema`)
"""
return obj._level
4 changes: 3 additions & 1 deletion narwhals/group_by.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ def agg(
Arguments:
aggs: Aggregations to compute for each group of the group by operation,
specified as positional arguments.
named_aggs: Additional aggregations, specified as keyword arguments.
Returns:
A new Dataframe.
Examples:
Group by one column or by multiple columns and call `agg` to compute
the grouped sum of another column.
Expand Down
18 changes: 15 additions & 3 deletions narwhals/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,25 @@ def __init__(
super().__init__(schema)

def names(self) -> list[str]:
"""Get the column names of the schema."""
"""Get the column names of the schema.
Returns:
Column names.
"""
return list(self.keys())

def dtypes(self) -> list[DType]:
"""Get the data types of the schema."""
"""Get the data types of the schema.
Returns:
Data types of schema.
"""
return list(self.values())

def len(self) -> int:
"""Get the number of columns in the schema."""
"""Get the number of columns in the schema.
Returns:
Number of columns.
"""
return len(self)
18 changes: 18 additions & 0 deletions narwhals/selectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ def by_dtype(*dtypes: Any) -> Expr:
Arguments:
dtypes: one or data types to select
Returns:
A new expression.
Examples:
>>> import narwhals as nw
>>> import narwhals.selectors as ncs
Expand Down Expand Up @@ -55,6 +58,9 @@ def by_dtype(*dtypes: Any) -> Expr:
def numeric() -> Expr:
"""Select numeric columns.
Returns:
A new expression.
Examples:
>>> import narwhals as nw
>>> import narwhals.selectors as ncs
Expand Down Expand Up @@ -95,6 +101,9 @@ def numeric() -> Expr:
def boolean() -> Expr:
"""Select boolean columns.
Returns:
A new expression.
Examples:
>>> import narwhals as nw
>>> import narwhals.selectors as ncs
Expand Down Expand Up @@ -135,6 +144,9 @@ def boolean() -> Expr:
def string() -> Expr:
"""Select string columns.
Returns:
A new expression.
Examples:
>>> import narwhals as nw
>>> import narwhals.selectors as ncs
Expand Down Expand Up @@ -175,6 +187,9 @@ def string() -> Expr:
def categorical() -> Expr:
"""Select categorical columns.
Returns:
A new expression.
Examples:
>>> import narwhals as nw
>>> import narwhals.selectors as ncs
Expand Down Expand Up @@ -215,6 +230,9 @@ def categorical() -> Expr:
def all() -> Expr:
"""Select all columns.
Returns:
A new expression.
Examples:
>>> import narwhals as nw
>>> import narwhals.selectors as ncs
Expand Down
76 changes: 30 additions & 46 deletions narwhals/stable/v1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1090,58 +1090,25 @@ def narwhalify(
) -> Callable[..., Any]:
"""Decorate function so it becomes dataframe-agnostic.
`narwhalify` will try to convert any dataframe/series-like object into the narwhal
This will try to convert any dataframe/series-like object into the Narwhals
respective DataFrame/Series, while leaving the other parameters as they are.
Similarly, if the output of the function is a narwhals DataFrame or Series, it will be
Similarly, if the output of the function is a Narwhals DataFrame or Series, it will be
converted back to the original dataframe/series type, while if the output is another
type it will be left as is.
By setting `pass_through=False`, then every input and every output will be required to be a
dataframe/series-like object.
Instead of writing
```python
import narwhals as nw
def func(df):
df = nw.from_native(df, pass_through=True)
df = df.group_by("a").agg(nw.col("b").sum())
return nw.to_native(df)
```
you can just write
```python
import narwhals as nw
@nw.narwhalify
def func(df):
return df.group_by("a").agg(nw.col("b").sum())
```
You can also pass in extra arguments, e.g.
```python
@nw.narwhalify(eager_only=True)
```
that will get passed down to `nw.from_native`.
Arguments:
func: Function to wrap in a `from_native`-`to_native` block.
strict: Determine what happens if the object isn't supported by Narwhals:
strict: **Deprecated** (v1.13.0):
Please use `pass_through` instead. Note that `strict` is still available
(and won't emit a deprecation warning) if you use `narwhals.stable.v1`,
see [perfect backwards compatibility policy](https://narwhals-dev.github.io/narwhals/backcompat/).
Determine what happens if the object isn't supported by Narwhals:
- `True` (default): raise an error
- `False`: pass object through as-is
**Deprecated** (v1.13.0):
Please use `pass_through` instead. Note that `strict` is still available
(and won't emit a deprecation warning) if you use `narwhals.stable.v1`,
see [perfect backwards compatibility policy](https://narwhals-dev.github.io/narwhals/backcompat/).
pass_through: Determine what happens if the object isn't supported by Narwhals:
- `False` (default): raise an error
Expand All @@ -1151,6 +1118,24 @@ def func(df):
implement the Dataframe Interchange Protocol.
series_only: Whether to only allow series.
allow_series: Whether to allow series (default is only dataframe / lazyframe).
Returns:
Decorated function.
Examples:
Instead of writing
>>> import narwhals as nw
>>> def func(df):
... df = nw.from_native(df, pass_through=True)
... df = df.group_by("a").agg(nw.col("b").sum())
... return nw.to_native(df)
you can just write
>>> @nw.narwhalify
... def func(df):
... return df.group_by("a").agg(nw.col("b").sum())
"""
pass_through = validate_strict_and_pass_though(
strict, pass_through, pass_through_default=True, emit_deprecation_warning=False
Expand Down Expand Up @@ -2102,12 +2087,11 @@ def concat(
Arguments:
items: DataFrames, LazyFrames to concatenate.
how: {'vertical', 'horizontal'}
* vertical: Stacks Series from DataFrames vertically and fills with `null`
if the lengths don't match.
* horizontal: Stacks Series from DataFrames horizontally and fills with `null`
if the lengths don't match.
- vertical: Stacks Series from DataFrames vertically and fills with `null`
if the lengths don't match.
- horizontal: Stacks Series from DataFrames horizontally and fills with `null`
if the lengths don't match.
Returns:
A new DataFrame, Lazyframe resulting from the concatenation.
Expand Down
Loading

0 comments on commit bbf3a5f

Please sign in to comment.