8000 turned func into a property · matplotlib/matplotlib@e2d5181 · GitHub
[go: up one dir, main page]

Skip to content

Commit e2d5181

Browse files
committed
turned func into a property
1 parent a21c4a8 commit e2d5181

File tree

2s changed

+28
-14
lines changed

2 files changed

+28
-14
lines changed

lib/matplotlib/tests/test_ticker.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1066,6 +1066,11 @@ def test_other_builtins(self):
10661066
with pytest.raises(UserWarning, match=r'max is not'):
10671067
mticker.FuncFormatter(max)
10681068

1069+
def test_update(self):
1070+
formatter = mticker.FuncFormatter(lambda x, pos: f"{x}+{pos}")
1071+
assert "1+2" == formatter(1,2)
1072+
with pytest.raises(TypeError, match='3 arguments'):
1073+
formatter.func = lambda x, pos, error: "!"
10691074

10701075
class TestStrMethodFormatter:
10711076
test_data = [

lib/matplotlib/ticker.py

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -387,33 +387,42 @@ class FuncFormatter(Formatter):
387387
def __init__(self, func):
388388
self.func = func
389389

390+
def __call__(self, x, pos=None):
391+
"""
392+
Return the value of the user defined function.
393+
394+
*x* and *pos* are passed through as-is.
395+
"""
396+
if self._nargs == 1:
397+
return self._func(x)
398+
return self._func(x, pos)
399+
400+
@property
401+
def func(self):
402+
return self._func
403+
404+
@func.setter
405+
def func(self, func):
406+
self._func = func
390407
if not isinstance(func, types.BuiltinFunctionType):
391-
self.nargs = len(inspect.signature(func).parameters)
408+
self._nargs = len(inspect.signature(func).parameters)
392409
elif (isinstance(getattr(func, "__self__"), str) and
393410
(getattr(func, "__name__", "") == "format")):
394411
#check if there's a format spec
395-
self.nargs = len([(_, _, fs, _) for (_, _, fs, _)
412+
self._nargs = len([(_, _, fs, _) for (_, _, fs, _)
396413
in string.Formatter().parse(func.__self__)
397414
if fs is not None])
398415
else:
399416
#finding argcount for other builtins is a mess
400-
self.nargs = 2
417+
self._nargs = 2
401418
cbook._warn_external(f"{func.__name__} is not supported "
402419
"and may not work as expected")
403-
if self.nargs not in [1, 2]:
404-
raise TypeError(f"{func.__name__} takes {self.nargs} arguments. "
420+
if self._nargs not in [1, 2]:
421+
raise TypeError(f"{func.__name__} takes {self._nargs} arguments. "
405422
"FuncFormatter functions take at most 2: "
406423
"x (required), pos (optional).")
424+
407425

408-
def __call__(self, x, pos=None):
409-
"""
410-
Return the value of the user defined function.
411-
412-
*x* and *pos* are passed through as-is.
413-
"""
414-
if self.nargs == 1:
415-
return self.func(x)
416-
return self.func(x, pos)
417426

418427

419428
class FormatStrFormatter(Formatter):

0 commit comments

Comments
 (0)
0