Skip to content

Commit ae813e2

Browse files
committed
Centralized code for config = <bool>
line_profiler/cli_utils.py[i]::get_cli_config() Rolled back last commit line_profiler/explicit_profiler.py[i]::GlobalProfiler - Updated docstring - Added missing `config` argument to `.__init__()` in the stub file line_profiler/line_profiler.py Removed wrapper function around `line_profiler.toml_config.get_config()` line_profiler/toml_config.py[i]::get_config() Added handling for `config = <bool>`: - `False`: don't look up or load any user-supplied config and just use the default - `True`: same as `None` (default behavior) tests/test_toml_config.py::test_config_lookup_hierarchy() Now also testing `get_config(True)` and `get_config(False)`
1 parent 012e65e commit ae813e2

8 files changed

+34
-38
lines changed

line_profiler/cli_utils.py

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def add_argument(parser_like, *args,
6767
return action
6868

6969

70-
def get_cli_config(subtable, /, config=None, *args, **kwargs):
70+
def get_cli_config(subtable, /, *args, **kwargs):
7171
"""
7272
Get the `tool.line_profiler.<subtable>` configs and normalize
7373
its keys (`some-key` -> `some_key`).
@@ -76,14 +76,6 @@ def get_cli_config(subtable, /, config=None, *args, **kwargs):
7676
subtable (str):
7777
Name of the subtable the CLI app should refer to (e.g.
7878
'kernprof')
79-
config (Union[str, PurePath, bool, None]):
80-
Optional filename from which to load configurations (e.g.
81-
output column widths);
82-
default (= `True` or `None`) is to look for a config file
83-
based on the environment variable `${LINE_PROFILER_RC}` and
84-
path-based lookup;
85-
passing `False` disables all lookup and falls back to the
86-
default configuration
8779
*args, **kwargs
8880
Passed to `line_profiler.toml_config.get_config()`
8981
@@ -96,12 +88,7 @@ def get_cli_config(subtable, /, config=None, *args, **kwargs):
9688
- `path`: absolute path to the config file whence the
9789
config options are loaded
9890
"""
99-
if config in (True,):
100-
config = None
101-
if config in (False,):
102-
conf, source = get_default_config()
103-
else:
104-
conf, source = get_config(config, *args, **kwargs)
91+
conf, source = get_config(*args, **kwargs)
10592
cli_conf = {key.replace('-', '_'): value
10693
for key, value in conf[subtable].items()}
10794
return cli_conf, source

line_profiler/cli_utils.pyi

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ def add_argument(parser_like: ParserLike[A_co], *args,
3333

3434

3535
def get_cli_config(subtable: str, /,
36-
config: Union[str, pathlib.PurePath, bool, None] = None,
3736
*args, **kwargs) -> Tuple[dict, pathlib.Path]:
3837
...
3938

line_profiler/explicit_profiler.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -181,16 +181,18 @@ class GlobalProfiler:
181181
The :py:obj:`line_profile.profile` decorator is an instance of this object.
182182
183183
Arguments:
184-
config (Union[str, PurePath, None]):
184+
config (Union[str, PurePath, bool, None]):
185185
Optional TOML config file from which to load the
186186
configurations (see Attributes);
187-
if not explicitly given, it is either resolved from the
188-
``LINE_PROFILER_RC`` environment variable or looked up among
189-
the current directory or its ancestors.
190-
Should all that fail, the default config file at
187+
if not explicitly given (= ``True`` or ``None``), it is
188+
either resolved from the ``LINE_PROFILER_RC`` environment
189+
variable or looked up among the current directory or its
190+
ancestors. Should all that fail, the default config file at
191191
``importlib.resources.path('line_profiler.rc',
192192
'line_profiler.toml')``
193-
is used.
193+
is used;
194+
passing ``False`` disables all lookup and falls back to the
195+
default configuration
194196
195197
Attributes:
196198
setup_config (Dict[str, List[str]]):

line_profiler/explicit_profiler.pyi

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
from pathlib import PurePath
12
from typing import Dict
23
from typing import List
34
from typing import Callable
5+
from typing import Union
46
from _typeshed import Incomplete
57

68

@@ -11,7 +13,8 @@ class GlobalProfiler:
1113
show_config: Dict[str, bool]
1214
enabled: bool | None
1315

14-
def __init__(self) -> None:
16+
def __init__(self,
17+
config: Union[str, PurePath, bool, None] = None) -> None:
1518
...
1619

1720
def enable(self, output_prefix: Incomplete | None = ...) -> None:

line_profiler/line_profiler.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
is_property, is_cached_property,
2525
is_boundmethod, is_classmethod, is_staticmethod,
2626
is_partial, is_partialmethod)
27-
from .toml_config import get_config, get_default_config
27+
from .toml_config import get_config
2828
from .cli_utils import (
2929
add_argument, get_cli_config, positive_float, short_string_path)
3030

@@ -38,15 +38,7 @@
3838
@functools.lru_cache()
3939
def get_minimum_column_widths():
4040
return types.MappingProxyType(
41-
get_default_config()[0]['show']['column_widths'])
42-
43-
44-
def _get_config(config):
45-
if config in (True,):
46-
config = None
47-
if config in (False,):
48-
return get_default_config()
49-
return get_config(config=config)
41+
get_config(False)[0]['show']['column_widths'])
5042

5143

5244
def load_ipython_extension(ip):
@@ -297,7 +289,7 @@ def show_func(filename, start_lineno, func_name, timings, unit,
297289
sublines = [''] * nlines
298290

299291
# Define minimum column sizes so text fits and usually looks consistent
300-
conf_column_sizes = _get_config(config)[0]['show']['column_widths']
292+
conf_column_sizes = get_config(config)[0]['show']['column_widths']
301293
default_column_sizes = {
302294
col: max(width, conf_column_sizes.get(col, width))
303295
for col, width in get_minimum_column_widths().items()}
@@ -428,7 +420,7 @@ def show_text(stats, unit, output_unit=None, stream=None, stripzeros=False,
428420
stats_order = sorted(stats.items())
429421

430422
# Pre-lookup the appropriate config file
431-
_, config = _get_config(config)
423+
_, config = get_config(config)
432424

433425
if details:
434426
# Show detailed per-line information for each function.

line_profiler/toml_config.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,9 +162,13 @@ def get_headers(table, *, include_implied=False):
162162
def get_config(config=None, *, read_env=True):
163163
"""
164164
Arguments:
165-
config (Union[str | PurePath | None]):
165+
config (Union[str, PurePath, bool, None]):
166166
Optional path to a specific TOML file;
167-
if provided, skip lookup and just try to read from that file
167+
if a (string) path, skip lookup and just try to read from
168+
that file;
169+
if `None` or `True`, use lookup to resolve to the correct
170+
file;
171+
if `False`, skip lookup and just use the default configs
168172
read_env (bool):
169173
Whether to read the environment variable
170174
`${LINE_PROFILER_RC}` for a config file (instead of moving
@@ -203,6 +207,11 @@ def merge(template, supplied):
203207
return result
204208

205209
default_conf, default_source = get_default_config()
210+
if config in (True, False):
211+
if config:
212+
config = None
213+
else:
214+
return default_conf, default_source
206215
if config is not None:
207216
# Promote to `Path` (and catch type errors) early
208217
config = pathlib.Path(config)

line_profiler/toml_config.pyi

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def get_headers(table: NestedTable[K, Any], *,
3333
...
3434

3535

36-
def get_config(config: Union[str, pathlib.PurePath, None] = None, *,
36+
def get_config(config: Union[str, pathlib.PurePath, bool, None] = None, *,
3737
read_env: bool = True) -> Config:
3838
...
3939

tests/test_toml_config.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,7 @@ def test_config_lookup_hierarchy(monkeypatch: pytest.MonkeyPatch,
139139
get_config(highest_priority)
140140
highest_priority.touch()
141141
assert get_config(highest_priority)[1].samefile(highest_priority)
142+
# Also test that `True` is equivalent to the default behavior
143+
# (`None`), and `False` to disabling all lookup
144+
assert get_config(True)[1].samefile(high_priority)
145+
assert get_config(False)[1].samefile(default)

0 commit comments

Comments
 (0)