Skip to content

Commit 218cbf0

Browse files
authored
0.6.4 (#50)
* Add ImproperUseError to distinguish node retrieving error from improper varname use #49 * 0.6.4 * Update CHANGELOG
1 parent c31b9b5 commit 218cbf0

File tree

9 files changed

+52
-20
lines changed

9 files changed

+52
-20
lines changed

.pylintrc

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,8 @@ disable=print-statement,
157157
too-many-locals,
158158
not-callable,
159159
unsubscriptable-object,
160-
unused-arguments
160+
unused-arguments,
161+
fixme
161162

162163
# Enable the message, report, category or checker with the given id(s). You can
163164
# either give multiple identifier separated by comma (,) or put this option
@@ -306,12 +307,20 @@ function-naming-style=snake_case
306307
#function-rgx=
307308

308309
# Good variable names which should always be accepted, separated by a comma.
309-
good-names=i,
310+
good-names=a,
311+
b,
312+
c,
313+
i,
310314
j,
311315
k,
316+
n,
312317
x,
313318
y,
314319
z,
320+
fn,
321+
df,
322+
pd,
323+
sd,
315324
np,
316325
gc,
317326
nn,
@@ -327,6 +336,7 @@ good-names=i,
327336
tf,
328337
on,
329338
op,
339+
wt,
330340
Run,
331341
_
332342

@@ -457,7 +467,7 @@ indent-string=' '
457467
max-line-length=80
458468

459469
# Maximum number of lines in a module.
460-
max-module-lines=1000
470+
max-module-lines=1500
461471

462472
# List of optional constructs for which whitespace checking is disabled. `dict-
463473
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.

README.rst

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -155,11 +155,6 @@ Retrieving the variable names using ``varname(...)``
155155
156156
func = asyncio.run(function()) # func == 'func'
157157
158-
# you can switch it off by:
159-
# config.ignore_stdlib = False
160-
# then you have to specify the library yourself:
161-
# varname(ignore=[asyncio])
162-
163158
*
164159
Retrieving name of a class instance
165160

docs/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
## v0.6.4
2+
- Add ImproperUseError to distinguish node retrieving error from improper varname use #49
3+
14
## v0.6.3
25
- Fix standard library ignoring ignores 3rd-party libraries under site-packages/
36
- Allow pathlib.Path object to be used in ignore items

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "poetry.masonry.api"
44

55
[tool.poetry]
66
name = "varname"
7-
version = "0.6.3"
7+
version = "0.6.4"
88
description = "Dark magics about variable names in python."
99
authors = [ "pwwang <[email protected]>",]
1010
license = "MIT"

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
setup(
2525
long_description=readme,
2626
name='varname',
27-
version='0.6.3',
27+
version='0.6.4',
2828
description='Dark magics about variable names in python.',
2929
python_requires='==3.*,>=3.6.0',
3030
project_urls={"homepage": "https://github.com/pwwang/python-varname",

tests/test_varname.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from executing import Source
88
from varname import *
99
from varname.helpers import *
10-
from varname.utils import get_node
10+
from varname.utils import ImproperUseError, get_node
1111

1212

1313
from .conftest import run_async, module_from_source
@@ -93,11 +93,11 @@ def test_single_var_lhs_required():
9393
def function():
9494
return varname()
9595

96-
with pytest.raises(VarnameRetrievingError,
96+
with pytest.raises(ImproperUseError,
9797
match='Expect a single variable on left-hand side'):
9898
x, y = function()
9999

100-
with pytest.raises(VarnameRetrievingError):
100+
with pytest.raises(ImproperUseError):
101101
x, y = function(), function()
102102

103103
def test_multi_vars_lhs():
@@ -122,7 +122,7 @@ def function():
122122

123123
# Not all LHS are variables
124124
with pytest.raises(
125-
VarnameRetrievingError,
125+
ImproperUseError,
126126
match='Can only get name of a variable or attribute, not Starred'
127127
):
128128
a, *b = function()

varname/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33
from .utils import (
44
config,
55
VarnameRetrievingError,
6+
ImproperUseError,
67
QualnameNonUniqueError,
78
NonVariableArgumentError,
89
MultiTargetAssignmentWarning,
910
MaybeDecoratedFunctionWarning
1011
)
1112
from .core import varname, nameof, will, argname
1213

13-
__version__ = "0.6.3"
14+
__version__ = "0.6.4"

varname/core.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
get_function_called_argname,
1616
parse_argname_subscript,
1717
VarnameRetrievingError,
18+
ImproperUseError,
1819
NonVariableArgumentError,
1920
MultiTargetAssignmentWarning
2021
)
@@ -62,9 +63,12 @@ class instantiation.
6263
If `True`, this function returns a tuple of the variable names,
6364
even there is only one variable on LHS.
6465
If `False`, and multiple variables on LHS, a
65-
`VarnameRetrievingError` will be raised.
66+
`ImproperUseError` will be raised.
6667
raise_exc: Whether we should raise an exception if failed
67-
to retrieve the name.
68+
to retrieve the ast node.
69+
Note that set this to `False` will not supress the exception when
70+
the use of `varname` is improper (i.e. multiple variables on
71+
LHS with `multi_vars` is `False`). See `Raises/ImproperUseError`.
6872
6973
Returns:
7074
The variable name, or `None` when `raise_exc` is `False` and
@@ -78,6 +82,11 @@ class instantiation.
7882
when we are unable to retrieve the variable name and `raise_exc`
7983
is set to `True`.
8084
85+
ImproperUseError: When the use of `varname()` is improper. For example:
86+
- When LHS is not an `ast.Name` or `ast.Attribute` node or not a
87+
list/tuple of them
88+
- When there are multiple variables on LHS but `multi_vars` is False
89+
8190
UserWarning: When there are multiple target
8291
in the assign node. (e.g: `a = b = func()`, in such a case,
8392
`b == 'a'`, may not be the case you want)
@@ -118,7 +127,7 @@ class instantiation.
118127
return names
119128

120129
if len(names) > 1:
121-
raise VarnameRetrievingError(
130+
raise ImproperUseError(
122131
f"Expect a single variable on left-hand side, got {len(names)}."
123132
)
124133

varname/utils.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,13 +59,27 @@ class NonVariableArgumentError(Exception):
5959
"""When vars_only is True but try to retrieve name of
6060
a non-variable argument"""
6161

62+
class ImproperUseError(VarnameRetrievingError):
63+
"""When varname() is improperly used"""
64+
def __init__(self, message: str) -> None:
65+
message = (
66+
f"{message}\n\n"
67+
"(Warning: `ImproperUseError` is a subclass of "
68+
"`VarnameRetrievingError` for now for backward compatibility, "
69+
"so you can still use `VarnameRetrievingError` to catch it. "
70+
"But it will be independent of `VarnameRetrievingError` "
71+
"in the future.)"
72+
)
73+
super().__init__(message)
74+
6275
class MaybeDecoratedFunctionWarning(Warning):
6376
"""When a suspecious decorated function used as ignore function directly"""
6477

6578
class MultiTargetAssignmentWarning(Warning):
6679
"""When varname tries to retrieve variable name in
6780
a multi-target assignment"""
6881

82+
6983
@lru_cache()
7084
def cached_getmodule(codeobj: CodeType):
7185
"""Cached version of inspect.getmodule"""
@@ -125,7 +139,7 @@ def lookfor_parent_assign(node: ast.AST) -> Optional[ast.Assign]:
125139
def node_name(node: ast.AST) -> Optional[Union[str, Tuple[Union[str, tuple]]]]:
126140
"""Get the node node name.
127141
128-
Raises VarnameRetrievingError when failed
142+
Raises ImproperUseError when failed
129143
"""
130144
if isinstance(node, ast.Name):
131145
return node.id
@@ -134,7 +148,7 @@ def node_name(node: ast.AST) -> Optional[Union[str, Tuple[Union[str, tuple]]]]:
134148
if isinstance(node, (ast.List, ast.Tuple)):
135149
return tuple(node_name(elem) for elem in node.elts)
136150

137-
raise VarnameRetrievingError(
151+
raise ImproperUseError(
138152
f"Can only get name of a variable or attribute, "
139153
f"not {ast.dump(node)}"
140154
)

0 commit comments

Comments
 (0)