Skip to content

Commit d5d2422

Browse files
authored
BREAKING: bytes annotation now re-encodes the corresponding parameter back to bytes (#89)
This also adds tests for using pathlib.Path types, and removes old compatibility for pre-pathlib Python releases (<=3.3)
1 parent ea1eb60 commit d5d2422

File tree

2 files changed

+23
-8
lines changed

2 files changed

+23
-8
lines changed

clize/parser.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import itertools
1010
import inspect
11+
import os
1112
import typing
1213
from functools import partial, wraps
1314
import pathlib
@@ -265,26 +266,30 @@ def identity(x=None):
265266
return x
266267

267268

269+
@value_converter(name='BYTES')
270+
def convert_back_to_bytes(arg):
271+
return os.fsencode(arg)
272+
273+
268274
@value_converter(name='BOOL')
269275
def is_true(arg):
270276
return arg.lower() not in ('', '0', 'n', 'no', 'f', 'false')
271277

272278

279+
@value_converter(name='PATH')
280+
def concrete_path_converter(arg):
281+
return pathlib.Path(arg)
282+
283+
273284
_implicit_converters = {
274285
int: int,
275286
float: float,
276287
bool: is_true,
277288
str: identity,
278-
bytes: identity,
289+
bytes: convert_back_to_bytes,
290+
pathlib.PurePath: concrete_path_converter
279291
}
280292

281-
if pathlib:
282-
@value_converter(name='PATH')
283-
def path_converter(arg):
284-
return pathlib.Path(arg)
285-
286-
_implicit_converters[pathlib.PurePath] = path_converter
287-
288293

289294
def get_value_converter(annotation):
290295
try:

clize/tests/test_parser.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# COPYING for details.
44
import functools
55
import inspect
6+
import os
67
import pathlib
78
import typing
89
import warnings
@@ -439,6 +440,15 @@ def _test(self, sig, str_rep, args, posargs, kwargs, *, make_signature):
439440

440441
ignored = s('one:P.I'), '', (), [], {}
441442

443+
bytes = s("a: bytes"), 'a', ('\u1234',), [os.fsencode('\u1234')], {}
444+
bytes_named = s("*, a: bytes"), '-a BYTES', ('-a\u1234',), [], {'a': os.fsencode('\u1234')}
445+
446+
path = s("*, a: ann", ann=pathlib.Path), '-a PATH', ('-a./abc/def',), [], {'a': pathlib.Path('./abc/def')}
447+
path_default = (
448+
s("*, a = default", default=pathlib.Path('./abc',)),
449+
'[-a PATH]', ('-a./def',), [], {'a': pathlib.Path('./def')},
450+
)
451+
442452
def test_converter_ignore(self):
443453
@parser.parameter_converter
444454
def conv(param, annotations, *, type_annotation):

0 commit comments

Comments
 (0)