bpo-29901 簡介
- Title: Support path-like objects in zipapp
- Create By: Serhiy Storchaka
- Solved By: Serhiy Storchaka
- BPO: http://bugs.python.org/issue29901
- PR815: https://github.com/python/cpython/pull/815
- Components: Library (Lib)
- Versions: Python 3.7
- Stage: resolved
- Type: enhancement
新知
- os.PathLike: https://docs.python.org/3/library/os.html#os.PathLike
- path-like object: https://docs.python.org/3.7/glossary.html#term-path-like-object
- Lib/zipapp (from version 3.5): https://docs.python.org/3/library/zipapp.html
- Lib/pathlib (from version 3.4): https://docs.python.org/3/library/pathlib.html
技巧
isinstance 的 classinfo 可以傳入 tuple
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
diff –git a/Lib/zipapp.py b/Lib/zipapp.py index eceb91de1a..c23b788d1c 100644 — a/Lib/zipapp.py +++ b/Lib/zipapp.py @@ -36,9 +36,7 @@ class ZipAppError(ValueError): @contextlib.contextmanager def _maybe_open(archive, mode): – if isinstance(archive, pathlib.Path): – archive = str(archive) – if isinstance(archive, str): + if isinstance(archive, (str, os.PathLike)): with open(archive, mode) as f: yield f else: |
from Python 3.6 docs:
isinstance
(object, classinfo)- Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns false. If classinfo is a tuple of type objects (or recursively, other such tuples), return true if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a
TypeError
exception is raised.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
>>> i = 10 >>> isinstance(i, int) True >>> isinstance(i, (str, int)) True >>> isinstance(i, (int, str)) True >>> isinstance(i, (bytes, str)) False >>> isinstance(i, ‘foo’) Traceback (most recent call last): File “<stdin>”, line 1, in <module> TypeError: isinstance() arg 2 must be a type or tuple of types >>> isinstance(i, (5, ‘test’)) Traceback (most recent call last): File “<stdin>”, line 1, in <module> TypeError: isinstance() arg 2 must be a type or tuple of types |
ZipFile itself converts the archive name to POSIX format. But I think it is better to do this explicity. Maybe implicit conversion will be deprecated in future.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
diff —git a/Lib/zipapp.py b/Lib/zipapp.py index eceb91de1a..fc7feb3218 100644 —– a/Lib/zipapp.py +++ b/Lib/zipapp.py @@ –135,10 +136,9 @@ def create_archive(source, target=None, interpreter=None, main=None): with _maybe_open(target, ‘wb’) as fd: _write_file_prefix(fd, interpreter) with zipfile.ZipFile(fd, ‘w’) as z: – root = pathlib.Path(source) – for child in root.rglob(‘*’): – arcname = str(child.relative_to(root)) – z.write(str(child), arcname) + for child in source.rglob(‘*’): + arcname = child.relative_to(source).as_posix() + z.write(child, arcname) if main_py: z.writestr(‘__main__.py’, main_py.encode(‘utf-8’)) |
Leave a Reply