4 ms·
> test_path = datasets_root / dataset / 'test' > Previously it was always tempting to use string concatenation (concise, but obviously bad), now with pathlib t
by jstimpfle 9y ago
> test_path = datasets_root / dataset / 'test'
> Previously it was always tempting to use string concatenation (concise, but obviously bad), now with pathlib the code is safe, concise, and readable.
This is the kind of feature that I'm wary to use even in scripts: questionable benefit, and probably too clever.
- metaobject 9y agoI don't have a machine available right now, but I wonder what happens if two adjacent path elements are integers? Does it perform division instead of path/string concatenation?
- lgas 9y agoTypeError: expected str, bytes or os.PathLike object, not int
- maxerickson 9y agoThe Path object won't construct a path from an integer. >>> from pathlib import Path >>> p=Path(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.6/pathlib.py", line 979, in __new__ self = cls._from_parts(args, init=False) File "/usr/lib/python3.6/pathlib.py", line 654, in _from_parts drv, root, parts = self._parse_args(args) File "/usr/lib/python3.6/pathlib.py", line 638, in _parse_args a = os.fspath(a) TypeError: expected str, bytes or os.PathLike object, not int >>> So what happens if the paths are numbers? They are treated like any other characters.
- sametmax 9y agop=Path(str(1)) Python is strongly typed.
- maxerickson 9y agoYes, that's pretty much the question metaobject was asking. Should I have said "numeric characters" or "numeric strings" in my last paragraph instead of numbers?
- latte 9y agoYou can't concatenate a path with an integer: >>> Path.cwd() / 1 TypeError: argument should be a path or str object, not <class 'int'> Also, note that the '/' operator is left-associative, so even if you have two adjacent numbers when joining paths, there will be no division.
- sametmax 9y agoBenefit is huge: it's readable, easy to type, and takes care of joining with proper "/" or "\" depending of the plateform.
- jstimpfle 9y agoI'll challenge you: You shouldn't have many paths, should keep them at a centralized location in the code, and there you could just use a normal function with a proper self-documenting name. It's not like programs consist of path operations to a significant degree, so using fancy syntactic sugar doesn't seem like a worthwhile optimization to me. At all.
- sametmax 9y agoYou say that because you are not a sysadmin. Python user base is very rich.