On Sun, 14 Oct 2012 21:48:59 +1100
Steven D'Aprano
Ah, I wondered if anyone else had picked up on that. When I read the PEP, I was concerned about the mental conflict between iteration and indexing of Path objects: given a Path p the sequence p[0] p[1] p[2] ... does something completely different from iterating over p directly.
p[0] p[1] etc. are just TypeErrors:
p = Path('.') p[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pathlib.py", line 951, in __getitem__ return self._make_child((key,)) File "pathlib.py", line 1090, in _make_child return self._from_parts(parts) File "pathlib.py", line 719, in _from_parts drv, root, parts = self._parse_args(args) File "pathlib.py", line 711, in _parse_args % type(a)) TypeError: argument should be a path or str object, not
So, yes, it's doing "something different", but there is little chance of silent bugs :-)
-1 on iteration over the children. Instead, use:
for child in p.walk(): ...
which has the huge benefit that the walk method can take arguments as needed, such as the args os.walk takes:
topdown=True, onerror=None, followlinks=False
Judging by its name and signature, walk() would be a recursive operation, while iterating on a path isn't (it only gets you the children).
+1 on indexing giving path components, although the side effect of this is that you automatically get iteration via the sequence protocol. So be it -- I don't think we should be scared to *choose* an iteration model, just because there are other potential models.
There is already a .parts property which does exactly that: http://www.python.org/dev/peps/pep-0428/#sequence-like-access The problem with enabling sequence access *on the path object* is that you get confusion with str's own sequencing behaviour, if you happen to pass a str instead of a Path, or the reverse. Which is explained briefly here: http://www.python.org/dev/peps/pep-0428/#no-confusion-with-builtins Regards Antoine. -- Software development and contracting: http://pro.pitrou.net