Upload 3580 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+36
- Pytorch/.nonadminAdded
- Pytorch/DLLs/_asyncio.pydAdded
- Pytorch/DLLs/_bz2.pydAdded
- Pytorch/DLLs/_ctypes.pydAdded
- Pytorch/DLLs/_ctypes_test.pydAdded
- Pytorch/DLLs/_decimal.pydAdded
- Pytorch/DLLs/_elementtree.pydAdded
- Pytorch/DLLs/_hashlib.pydAdded
- Pytorch/DLLs/_lzma.pydAdded
- Pytorch/DLLs/_msi.pydAdded
- Pytorch/DLLs/_multiprocessing.pydAdded
- Pytorch/DLLs/_overlapped.pydAdded
- Pytorch/DLLs/_queue.pydAdded
- Pytorch/DLLs/_socket.pydAdded
- Pytorch/DLLs/_sqlite3.pydAdded
- Pytorch/DLLs/_ssl.pydAdded
- Pytorch/DLLs/_testbuffer.pydAdded
- Pytorch/DLLs/_testcapi.pydAdded
- Pytorch/DLLs/_testconsole.pydAdded
- Pytorch/DLLs/_testimportmultiple.pydAdded
- Pytorch/DLLs/_testinternalcapi.pydAdded
- Pytorch/DLLs/_testmultiphase.pydAdded
- Pytorch/DLLs/_tkinter.pydAdded
- Pytorch/DLLs/_uuid.pydAdded
- Pytorch/DLLs/_zoneinfo.pydAdded
- Pytorch/DLLs/py.icoAdded
- Pytorch/DLLs/pyc.icoAdded
- Pytorch/DLLs/pyexpat.pydAdded
- Pytorch/DLLs/select.pydAdded
- Pytorch/DLLs/unicodedata.pydAdded+3
- Pytorch/DLLs/winsound.pydAdded
- Pytorch/DLLs/xxlimited.pydAdded
- Pytorch/DLLs/xxlimited_35.pydAdded
- Pytorch/LICENSE_PYTHON.txtAdded+279
- Pytorch/Lib/abc.pyAdded+188
- Pytorch/Lib/aifc.pyAdded+947
- Pytorch/Lib/antigravity.pyAdded+17
- Pytorch/Lib/argparse.pyAdded
- Pytorch/Lib/ast.pyAdded+1709
- Pytorch/Lib/asynchat.pyAdded+315
- Pytorch/Lib/asyncio/__init__.pyAdded+43
- Pytorch/Lib/asyncio/__main__.pyAdded+125
- Pytorch/Lib/asyncio/__pycache__/__init__.cpython-310.pycAdded
- Pytorch/Lib/asyncio/__pycache__/__main__.cpython-310.pycAdded
- Pytorch/Lib/asyncio/__pycache__/base_events.cpython-310.pycAdded
- Pytorch/Lib/asyncio/__pycache__/base_futures.cpython-310.pycAdded
- Pytorch/Lib/asyncio/__pycache__/base_subprocess.cpython-310.pycAdded
- Pytorch/Lib/asyncio/__pycache__/base_tasks.cpython-310.pycAdded
- Pytorch/Lib/asyncio/__pycache__/constants.cpython-310.pycAdded
32 unmodified lines33343536373839404142434445464748495051525354555657585960616263646566676869707132 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textPytorch/DLLs/unicodedata.pyd filter=lfs diff=lfs merge=lfs -textPytorch/Lib/ensurepip/_bundled/pip-23.0.1-py3-none-any.whl filter=lfs diff=lfs merge=lfs -textPytorch/Lib/ensurepip/_bundled/setuptools-65.5.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/libcrypto-3-x64.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/libcrypto-3-x64.pdb filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/libiomp5md.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/libiomp5md.pdb filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/libssl-3-x64.pdb filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_avx.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_avx2.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_avx512.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_core.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_def.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_intel_thread.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_mc.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_mc3.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_pgi_thread.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_rt.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_scalapack_ilp64.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_scalapack_lp64.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_sequential.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_tbb_thread.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_vml_avx.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_vml_avx2.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_vml_avx512.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_vml_cmpt.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_vml_def.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_vml_mc.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/bin/mkl_vml_mc3.2.dll filter=lfs diff=lfs merge=lfs -textPytorch/Library/lib/libcrypto.lib filter=lfs diff=lfs merge=lfs -textPytorch/Library/lib/liblzma_static.lib filter=lfs diff=lfs merge=lfs -textPytorch/Library/lib/libomp-device-svml.obj filter=lfs diff=lfs merge=lfs -textPytorch/Library/lib/sqlite3.44.2/sqlite3442t.dll filter=lfs diff=lfs merge=lfs -textPytorch/python310.dll filter=lfs diff=lfs merge=lfs -textPytorch/python310.pdb filter=lfs diff=lfs merge=lfs -textPytorch/ucrtbase.dll filter=lfs diff=lfs merge=lfs -text123version https://git-lfs.github.com/spec/v1oid sha256:dc0b7e48b8d7319f515877b98e086b8a85b24a47c0cc8b1d8a127d72d94272bcsize 1121560123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279A. HISTORY OF THE SOFTWARE==========================
Python was created in the early 1990s by Guido van Rossum at StichtingMathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlandsas a successor of a language called ABC. Guido remains Python'sprincipal author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation forNational Research Initiatives (CNRI, see https://www.cnri.reston.va.us)in Reston, Virginia where he released several versions of thesoftware.
In May 2000, Guido and the Python core development team moved toBeOpen.com to form the BeOpen PythonLabs team. In October of the sameyear, the PythonLabs team moved to Digital Creations, which becameZope Corporation. In 2001, the Python Software Foundation (PSF, seehttps://www.python.org/psf/) was formed, a non-profit organizationcreated specifically to own Python-related Intellectual Property.Zope Corporation was a sponsoring member of the PSF.
All Python releases are Open Source (see https://opensource.org forthe Open Source Definition). Historically, most, but not all, Pythonreleases have also been GPL-compatible; the table below summarizesthe various releases.
Release Derived Year Owner GPL- from compatible? (1)
0.9.0 thru 1.2 1991-1995 CWI yes 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes 1.6 1.5.2 2000 CNRI no 2.0 1.6 2000 BeOpen.com no 1.6.1 1.6 2001 CNRI yes (2) 2.1 2.0+1.6.1 2001 PSF no 2.0.1 2.0+1.6.1 2001 PSF yes 2.1.1 2.1+2.0.1 2001 PSF yes 2.1.2 2.1.1 2002 PSF yes 2.1.3 2.1.2 2002 PSF yes 2.2 and above 2.1.1 2001-now PSF yes
Footnotes:
(1) GPL-compatible doesn't mean that we're distributing Python under the GPL. All Python licenses, unlike the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible licenses make it possible to combine Python with other software that is released under the GPL; the others don't.
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, because its license has a choice of law clause. According to CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 is "not incompatible" with the GPL.
Thanks to the many outside volunteers who have worked under Guido'sdirection to make these releases possible.
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON===============================================================
Python software and documentation are licensed under thePython Software Foundation License Version 2.
Starting with Python 3.8.6, examples, recipes, and other code inthe documentation are dual licensed under the PSF License Version 2and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses.The licenses are listed with code falling under that license.
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2--------------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation("PSF"), and the Individual or Organization ("Licensee") accessing andotherwise using this software ("Python") in source or binary form andits associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF herebygrants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,analyze, test, perform and/or display publicly, prepare derivative works,distribute, and otherwise use Python alone or in any derivative version,provided, however, that PSF's License Agreement and PSF's notice of copyright,i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation;All Rights Reserved" are retained in Python alone or in any derivative versionprepared by Licensee.
3. In the event Licensee prepares a derivative work that is based onor incorporates Python or any part thereof, and wants to makethe derivative work available to others as provided herein, thenLicensee hereby agrees to include in any such work a brief summary ofthe changes made to Python.
4. PSF is making Python available to Licensee on an "AS IS"basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS ORIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO ANDDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESSFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOTINFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHONFOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS ASA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a materialbreach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create anyrelationship of agency, partnership, or joint venture between PSF andLicensee. This License Agreement does not grant permission to use PSFtrademarks or trade name in a trademark sense to endorse or promoteproducts or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python, Licenseeagrees to be bound by the terms and conditions of this LicenseAgreement.
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0-------------------------------------------
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having anoffice at 160 Saratoga Avenue, Santa Clara, CA 95051, and theIndividual or Organization ("Licensee") accessing and otherwise usingthis software in source or binary form and its associateddocumentation ("the Software").
2. Subject to the terms and conditions of this BeOpen Python LicenseAgreement, BeOpen hereby grants Licensee a non-exclusive,royalty-free, world-wide license to reproduce, analyze, test, performand/or display publicly, prepare derivative works, distribute, andotherwise use the Software alone or in any derivative version,provided, however, that the BeOpen Python License is retained in theSoftware, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an "AS IS"basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS ORIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO ANDDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESSFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOTINFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THESOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSSAS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANYDERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a materialbreach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in allrespects by the law of the State of California, excluding conflict oflaw provisions. Nothing in this License Agreement shall be deemed tocreate any relationship of agency, partnership, or joint venturebetween BeOpen and Licensee. This License Agreement does not grantpermission to use BeOpen trademarks or trade names in a trademarksense to endorse or promote products or services of Licensee, or anythird party. As an exception, the "BeOpen Python" logos available athttp://www.pythonlabs.com/logos.html may be used according to thepermissions granted on that web page.
7. By copying, installing or otherwise using the software, Licenseeagrees to be bound by the terms and conditions of this LicenseAgreement.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1---------------------------------------
1. This LICENSE AGREEMENT is between the Corporation for NationalResearch Initiatives, having an office at 1895 Preston White Drive,Reston, VA 20191 ("CNRI"), and the Individual or Organization("Licensee") accessing and otherwise using Python 1.6.1 software insource or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, CNRIhereby grants Licensee a nonexclusive, royalty-free, world-widelicense to reproduce, analyze, test, perform and/or display publicly,prepare derivative works, distribute, and otherwise use Python 1.6.1alone or in any derivative version, provided, however, that CNRI'sLicense Agreement and CNRI's notice of copyright, i.e., "Copyright (c)1995-2001 Corporation for National Research Initiatives; All RightsReserved" are retained in Python 1.6.1 alone or in any derivativeversion prepared by Licensee. Alternately, in lieu of CNRI's LicenseAgreement, Licensee may substitute the following text (omitting thequotes): "Python 1.6.1 is made available subject to the terms andconditions in CNRI's License Agreement. This Agreement together withPython 1.6.1 may be located on the internet using the followingunique, persistent identifier (known as a handle): 1895.22/1013. ThisAgreement may also be obtained from a proxy server on the internetusing the following URL: http://hdl.handle.net/1895.22/1013".
3. In the event Licensee prepares a derivative work that is based onor incorporates Python 1.6.1 or any part thereof, and wants to makethe derivative work available to others as provided herein, thenLicensee hereby agrees to include in any such work a brief summary ofthe changes made to Python 1.6.1.
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS ORIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO ANDDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESSFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOTINFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS ASA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a materialbreach of its terms and conditions.
7. This License Agreement shall be governed by the federalintellectual property law of the United States, including withoutlimitation the federal copyright law, and, to the extent suchU.S. federal law does not apply, by the law of the Commonwealth ofVirginia, excluding Virginia's conflict of law provisions.Notwithstanding the foregoing, with regard to derivative works basedon Python 1.6.1 that incorporate non-separable material that waspreviously distributed under the GNU General Public License (GPL), thelaw of the Commonwealth of Virginia shall govern this LicenseAgreement only as to issues arising under or with respect toParagraphs 4, 5, and 7 of this License Agreement. Nothing in thisLicense Agreement shall be deemed to create any relationship ofagency, partnership, or joint venture between CNRI and Licensee. ThisLicense Agreement does not grant permission to use CNRI trademarks ortrade name in a trademark sense to endorse or promote products orservices of Licensee, or any third party.
8. By clicking on the "ACCEPT" button where indicated, or by copying,installing or otherwise using Python 1.6.1, Licensee agrees to bebound by the terms and conditions of this License Agreement.
ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2--------------------------------------------------
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and itsdocumentation for any purpose and without fee is hereby granted,provided that the above copyright notice appear in all copies and thatboth that copyright notice and this permission notice appear insupporting documentation, and that the name of Stichting MathematischCentrum or CWI not be used in advertising or publicity pertaining todistribution of the software without specific, written priorpermission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TOTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY ANDFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLEFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGESWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN ANACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUTOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION----------------------------------------------------------------------
Permission to use, copy, modify, and/or distribute this software for anypurpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITHREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITYAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROMLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OROTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE ORPERFORMANCE OF THIS SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188# Copyright 2007 Google, Inc. All Rights Reserved.# Licensed to PSF under a Contributor Agreement.
"""Abstract Base Classes (ABCs) according to PEP 3119."""
def abstractmethod(funcobj): """A decorator indicating abstract methods.
Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors.
Usage:
class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ... """ funcobj.__isabstractmethod__ = True return funcobj
class abstractclassmethod(classmethod): """A decorator indicating abstract classmethods.
Deprecated, use 'classmethod' with 'abstractmethod' instead:
class C(ABC): @classmethod @abstractmethod def my_abstract_classmethod(cls, ...): ...
"""
__isabstractmethod__ = True
def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable)
class abstractstaticmethod(staticmethod): """A decorator indicating abstract staticmethods.
Deprecated, use 'staticmethod' with 'abstractmethod' instead:
class C(ABC): @staticmethod @abstractmethod def my_abstract_staticmethod(...): ...
"""
__isabstractmethod__ = True
def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable)
class abstractproperty(property): """A decorator indicating abstract properties.
Deprecated, use 'property' with 'abstractmethod' instead:
class C(ABC): @property @abstractmethod def my_abstract_property(self): ...
"""
__isabstractmethod__ = True
try: from _abc import (get_cache_token, _abc_init, _abc_register, _abc_instancecheck, _abc_subclasscheck, _get_dump, _reset_registry, _reset_caches)except ImportError: from _py_abc import ABCMeta, get_cache_token ABCMeta.__module__ = 'abc'else: class ABCMeta(type): """Metaclass for defining Abstract Base Classes (ABCs).
Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()). """ def __new__(mcls, name, bases, namespace, **kwargs): cls = super().__new__(mcls, name, bases, namespace, **kwargs) _abc_init(cls) return cls
def register(cls, subclass): """Register a virtual subclass of an ABC.
Returns the subclass, to allow usage as a class decorator. """ return _abc_register(cls, subclass)
def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" return _abc_instancecheck(cls, instance)
def __subclasscheck__(cls, subclass): """Override for issubclass(subclass, cls).""" return _abc_subclasscheck(cls, subclass)
def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file) print(f"Inv. counter: {get_cache_token()}", file=file) (_abc_registry, _abc_cache, _abc_negative_cache, _abc_negative_cache_version) = _get_dump(cls) print(f"_abc_registry: {_abc_registry!r}", file=file) print(f"_abc_cache: {_abc_cache!r}", file=file) print(f"_abc_negative_cache: {_abc_negative_cache!r}", file=file) print(f"_abc_negative_cache_version: {_abc_negative_cache_version!r}", file=file)
def _abc_registry_clear(cls): """Clear the registry (for debugging or testing).""" _reset_registry(cls)
def _abc_caches_clear(cls): """Clear the caches (for debugging or testing).""" _reset_caches(cls)
def update_abstractmethods(cls): """Recalculate the set of abstract methods of an abstract class.
If a class has had one of its abstract methods implemented after the class was created, the method will not be considered implemented until this function is called. Alternatively, if a new abstract method has been added to the class, it will only be considered an abstract method of the class after this function is called.
This function should be called before any use is made of the class, usually in class decorators that add methods to the subject class.
Returns cls, to allow usage as a class decorator.
If cls is not an instance of ABCMeta, does nothing. """ if not hasattr(cls, '__abstractmethods__'): # We check for __abstractmethods__ here because cls might by a C # implementation or a python implementation (especially during # testing), and we want to handle both cases. return cls
abstracts = set() # Check the existing abstract methods of the parents, keep only the ones # that are not implemented. for scls in cls.__bases__: for name in getattr(scls, '__abstractmethods__', ()): value = getattr(cls, name, None) if getattr(value, "__isabstractmethod__", False): abstracts.add(name) # Also add any other newly added abstract methods. for name, value in cls.__dict__.items(): if getattr(value, "__isabstractmethod__", False): abstracts.add(name) cls.__abstractmethods__ = frozenset(abstracts) return cls
class ABC(metaclass=ABCMeta): """Helper class that provides a standard way to create an ABC using inheritance. """ __slots__ = ()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947"""Stuff to parse AIFF-C and AIFF files.
Unless explicitly stated otherwise, the description below is trueboth for AIFF-C files and AIFF files.
An AIFF-C file has the following structure.
+-----------------+ | FORM | +-----------------+ | <size> | +----+------------+ | | AIFC | | +------------+ | | <chunks> | | | . | | | . | | | . | +----+------------+
An AIFF file has the string "AIFF" instead of "AIFC".
A chunk consists of an identifier (4 bytes) followed by a size (4 bytes,big endian order), followed by the data. The size field does not includethe size of the 8 byte header.
The following chunk types are recognized.
FVER <version number of AIFF-C defining document> (AIFF-C only). MARK <# of markers> (2 bytes) list of markers: <marker ID> (2 bytes, must be > 0) <position> (4 bytes) <marker name> ("pstring") COMM <# of channels> (2 bytes) <# of sound frames> (4 bytes) <size of the samples> (2 bytes) <sampling frequency> (10 bytes, IEEE 80-bit extended floating point) in AIFF-C files only: <compression type> (4 bytes) <human-readable version of compression type> ("pstring") SSND <offset> (4 bytes, not used by this program) <blocksize> (4 bytes, not used by this program) <sound data>
A pstring consists of 1 byte length, a string of characters, and 0 or 1byte pad to make the total length even.
Usage.
Reading AIFF files: f = aifc.open(file, 'r')where file is either the name of a file or an open file pointer.The open file pointer must have methods read(), seek(), and close().In some types of audio files, if the setpos() method is not used,the seek() method is not necessary.
This returns an instance of a class with the following public methods: getnchannels() -- returns number of audio channels (1 for mono, 2 for stereo) getsampwidth() -- returns sample width in bytes getframerate() -- returns sampling frequency getnframes() -- returns number of audio frames getcomptype() -- returns compression type ('NONE' for AIFF files) getcompname() -- returns human-readable version of compression type ('not compressed' for AIFF files) getparams() -- returns a namedtuple consisting of all of the above in the above order getmarkers() -- get the list of marks in the audio file or None if there are no marks getmark(id) -- get mark with the specified id (raises an error if the mark does not exist) readframes(n) -- returns at most n frames of audio rewind() -- rewind to the beginning of the audio stream setpos(pos) -- seek to the specified position tell() -- return the current position close() -- close the instance (make it unusable)The position returned by tell(), the position given to setpos() andthe position of marks are all compatible and have nothing to do withthe actual position in the file.The close() method is called automatically when the class instanceis destroyed.
Writing AIFF files: f = aifc.open(file, 'w')where file is either the name of a file or an open file pointer.The open file pointer must have methods write(), tell(), seek(), andclose().
This returns an instance of a class with the following public methods: aiff() -- create an AIFF file (AIFF-C default) aifc() -- create an AIFF-C file setnchannels(n) -- set the number of channels setsampwidth(n) -- set the sample width setframerate(n) -- set the frame rate setnframes(n) -- set the number of frames setcomptype(type, name) -- set the compression type and the human-readable compression type setparams(tuple) -- set all parameters at once setmark(id, pos, name) -- add specified mark to the list of marks tell() -- return current position in output file (useful in combination with setmark()) writeframesraw(data) -- write audio frames without pathing up the file header writeframes(data) -- write audio frames and patch up the file header close() -- patch up the file header and close the output fileYou should set the parameters before the first writeframesraw orwriteframes. The total number of frames does not need to be set,but when it is set to the correct value, the header does not have tobe patched up.It is best to first set all parameters, perhaps possibly thecompression type, and then write audio frames using writeframesraw.When all frames have been written, either call writeframes(b'') orclose() to patch up the sizes in the header.Marks can be added anytime. If there are any marks, you must callclose() after all frames have been written.The close() method is called automatically when the class instanceis destroyed.
When a file is opened with the extension '.aiff', an AIFF file iswritten, otherwise an AIFF-C file is written. This default can bechanged by calling aiff() or aifc() before the first writeframes orwriteframesraw."""
import structimport builtinsimport warnings
__all__ = ["Error", "open"]
class Error(Exception): pass
_AIFC_version = 0xA2805140 # Version 1 of AIFF-C
def _read_long(file): try: return struct.unpack('>l', file.read(4))[0] except struct.error: raise EOFError from None
def _read_ulong(file): try: return struct.unpack('>L', file.read(4))[0] except struct.error: raise EOFError from None
def _read_short(file): try: return struct.unpack('>h', file.read(2))[0] except struct.error: raise EOFError from None
def _read_ushort(file): try: return struct.unpack('>H', file.read(2))[0] except struct.error: raise EOFError from None
def _read_string(file): length = ord(file.read(1)) if length == 0: data = b'' else: data = file.read(length) if length & 1 == 0: dummy = file.read(1) return data
_HUGE_VAL = 1.79769313486231e+308 # See <limits.h>
def _read_float(f): # 10 bytes expon = _read_short(f) # 2 bytes sign = 1 if expon < 0: sign = -1 expon = expon + 0x8000 himant = _read_ulong(f) # 4 bytes lomant = _read_ulong(f) # 4 bytes if expon == himant == lomant == 0: f = 0.0 elif expon == 0x7FFF: f = _HUGE_VAL else: expon = expon - 16383 f = (himant * 0x100000000 + lomant) * pow(2.0, expon - 63) return sign * f
def _write_short(f, x): f.write(struct.pack('>h', x))
def _write_ushort(f, x): f.write(struct.pack('>H', x))
def _write_long(f, x): f.write(struct.pack('>l', x))
def _write_ulong(f, x): f.write(struct.pack('>L', x))
def _write_string(f, s): if len(s) > 255: raise ValueError("string exceeds maximum pstring length") f.write(struct.pack('B', len(s))) f.write(s) if len(s) & 1 == 0: f.write(b'\x00')
def _write_float(f, x): import math if x < 0: sign = 0x8000 x = x * -1 else: sign = 0 if x == 0: expon = 0 himant = 0 lomant = 0 else: fmant, expon = math.frexp(x) if expon > 16384 or fmant >= 1 or fmant != fmant: # Infinity or NaN expon = sign|0x7FFF himant = 0 lomant = 0 else: # Finite expon = expon + 16382 if expon < 0: # denormalized fmant = math.ldexp(fmant, expon) expon = 0 expon = expon | sign fmant = math.ldexp(fmant, 32) fsmant = math.floor(fmant) himant = int(fsmant) fmant = math.ldexp(fmant - fsmant, 32) fsmant = math.floor(fmant) lomant = int(fsmant) _write_ushort(f, expon) _write_ulong(f, himant) _write_ulong(f, lomant)
from chunk import Chunkfrom collections import namedtuple
_aifc_params = namedtuple('_aifc_params', 'nchannels sampwidth framerate nframes comptype compname')
_aifc_params.nchannels.__doc__ = 'Number of audio channels (1 for mono, 2 for stereo)'_aifc_params.sampwidth.__doc__ = 'Sample width in bytes'_aifc_params.framerate.__doc__ = 'Sampling frequency'_aifc_params.nframes.__doc__ = 'Number of audio frames'_aifc_params.comptype.__doc__ = 'Compression type ("NONE" for AIFF files)'_aifc_params.compname.__doc__ = ("""\A human-readable version of the compression type('not compressed' for AIFF files)""")
class Aifc_read: # Variables used in this class: # # These variables are available to the user though appropriate # methods of this class: # _file -- the open file with methods read(), close(), and seek() # set through the __init__() method # _nchannels -- the number of audio channels # available through the getnchannels() method # _nframes -- the number of audio frames # available through the getnframes() method # _sampwidth -- the number of bytes per audio sample # available through the getsampwidth() method # _framerate -- the sampling frequency # available through the getframerate() method # _comptype -- the AIFF-C compression type ('NONE' if AIFF) # available through the getcomptype() method # _compname -- the human-readable AIFF-C compression type # available through the getcomptype() method # _markers -- the marks in the audio file # available through the getmarkers() and getmark() # methods # _soundpos -- the position in the audio stream # available through the tell() method, set through the # setpos() method # # These variables are used internally only: # _version -- the AIFF-C version number # _decomp -- the decompressor from builtin module cl # _comm_chunk_read -- 1 iff the COMM chunk has been read # _aifc -- 1 iff reading an AIFF-C file # _ssnd_seek_needed -- 1 iff positioned correctly in audio # file for readframes() # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk # _framesize -- size of one frame in the file
_file = None # Set here since __del__ checks it
def initfp(self, file): self._version = 0 self._convert = None self._markers = [] self._soundpos = 0 self._file = file chunk = Chunk(file) if chunk.getname() != b'FORM': raise Error('file does not start with FORM id') formdata = chunk.read(4) if formdata == b'AIFF': self._aifc = 0 elif formdata == b'AIFC': self._aifc = 1 else: raise Error('not an AIFF or AIFF-C file') self._comm_chunk_read = 0 self._ssnd_chunk = None while 1: self._ssnd_seek_needed = 1 try: chunk = Chunk(self._file) except EOFError: break chunkname = chunk.getname() if chunkname == b'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunkname == b'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 elif chunkname == b'FVER': self._version = _read_ulong(chunk) elif chunkname == b'MARK': self._readmark(chunk) chunk.skip() if not self._comm_chunk_read or not self._ssnd_chunk: raise Error('COMM chunk and/or SSND chunk missing')
def __init__(self, f): if isinstance(f, str): file_object = builtins.open(f, 'rb') try: self.initfp(file_object) except: file_object.close() raise else: # assume it is an open file object already self.initfp(f)
def __enter__(self): return self
def __exit__(self, *args): self.close()
# # User visible methods. # def getfp(self): return self._file
def rewind(self): self._ssnd_seek_needed = 1 self._soundpos = 0
def close(self): file = self._file if file is not None: self._file = None file.close()
def tell(self): return self._soundpos
def getnchannels(self): return self._nchannels
def getnframes(self): return self._nframes
def getsampwidth(self): return self._sampwidth
def getframerate(self): return self._framerate
def getcomptype(self): return self._comptype
def getcompname(self): return self._compname
## def getversion(self):## return self._version
def getparams(self): return _aifc_params(self.getnchannels(), self.getsampwidth(), self.getframerate(), self.getnframes(), self.getcomptype(), self.getcompname())
def getmarkers(self): if len(self._markers) == 0: return None return self._markers
def getmark(self, id): for marker in self._markers: if id == marker[0]: return marker raise Error('marker {0!r} does not exist'.format(id))
def setpos(self, pos): if pos < 0 or pos > self._nframes: raise Error('position not in range') self._soundpos = pos self._ssnd_seek_needed = 1
def readframes(self, nframes): if self._ssnd_seek_needed: self._ssnd_chunk.seek(0) dummy = self._ssnd_chunk.read(8) pos = self._soundpos * self._framesize if pos: self._ssnd_chunk.seek(pos + 8) self._ssnd_seek_needed = 0 if nframes == 0: return b'' data = self._ssnd_chunk.read(nframes * self._framesize) if self._convert and data: data = self._convert(data) self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth) return data
# # Internal methods. #
def _alaw2lin(self, data): import audioop return audioop.alaw2lin(data, 2)
def _ulaw2lin(self, data): import audioop return audioop.ulaw2lin(data, 2)
def _adpcm2lin(self, data): import audioop if not hasattr(self, '_adpcmstate'): # first time self._adpcmstate = None data, self._adpcmstate = audioop.adpcm2lin(data, 2, self._adpcmstate) return data
def _read_comm_chunk(self, chunk): self._nchannels = _read_short(chunk) self._nframes = _read_long(chunk) self._sampwidth = (_read_short(chunk) + 7) // 8 self._framerate = int(_read_float(chunk)) if self._sampwidth <= 0: raise Error('bad sample width') if self._nchannels <= 0: raise Error('bad # of channels') self._framesize = self._nchannels * self._sampwidth if self._aifc: #DEBUG: SGI's soundeditor produces a bad size :-( kludge = 0 if chunk.chunksize == 18: kludge = 1 warnings.warn('Warning: bad COMM chunk size') chunk.chunksize = 23 #DEBUG end self._comptype = chunk.read(4) #DEBUG start if kludge: length = ord(chunk.file.read(1)) if length & 1 == 0: length = length + 1 chunk.chunksize = chunk.chunksize + length chunk.file.seek(-1, 1) #DEBUG end self._compname = _read_string(chunk) if self._comptype != b'NONE': if self._comptype == b'G722': self._convert = self._adpcm2lin elif self._comptype in (b'ulaw', b'ULAW'): self._convert = self._ulaw2lin elif self._comptype in (b'alaw', b'ALAW'): self._convert = self._alaw2lin else: raise Error('unsupported compression type') self._sampwidth = 2 else: self._comptype = b'NONE' self._compname = b'not compressed'
def _readmark(self, chunk): nmarkers = _read_short(chunk) # Some files appear to contain invalid counts. # Cope with this by testing for EOF. try: for i in range(nmarkers): id = _read_short(chunk) pos = _read_long(chunk) name = _read_string(chunk) if pos or name: # some files appear to have # dummy markers consisting of # a position 0 and name '' self._markers.append((id, pos, name)) except EOFError: w = ('Warning: MARK chunk contains only %s marker%s instead of %s' % (len(self._markers), '' if len(self._markers) == 1 else 's', nmarkers)) warnings.warn(w)
class Aifc_write: # Variables used in this class: # # These variables are user settable through appropriate methods # of this class: # _file -- the open file with methods write(), close(), tell(), seek() # set through the __init__() method # _comptype -- the AIFF-C compression type ('NONE' in AIFF) # set through the setcomptype() or setparams() method # _compname -- the human-readable AIFF-C compression type # set through the setcomptype() or setparams() method # _nchannels -- the number of audio channels # set through the setnchannels() or setparams() method # _sampwidth -- the number of bytes per audio sample # set through the setsampwidth() or setparams() method # _framerate -- the sampling frequency # set through the setframerate() or setparams() method # _nframes -- the number of audio frames written to the header # set through the setnframes() or setparams() method # _aifc -- whether we're writing an AIFF-C file or an AIFF file # set through the aifc() method, reset through the # aiff() method # # These variables are used internally only: # _version -- the AIFF-C version number # _comp -- the compressor from builtin module cl # _nframeswritten -- the number of audio frames actually written # _datalength -- the size of the audio samples written to the header # _datawritten -- the size of the audio samples actually written
_file = None # Set here since __del__ checks it
def __init__(self, f): if isinstance(f, str): file_object = builtins.open(f, 'wb') try: self.initfp(file_object) except: file_object.close() raise
# treat .aiff file extensions as non-compressed audio if f.endswith('.aiff'): self._aifc = 0 else: # assume it is an open file object already self.initfp(f)
def initfp(self, file): self._file = file self._version = _AIFC_version self._comptype = b'NONE' self._compname = b'not compressed' self._convert = None self._nchannels = 0 self._sampwidth = 0 self._framerate = 0 self._nframes = 0 self._nframeswritten = 0 self._datawritten = 0 self._datalength = 0 self._markers = [] self._marklength = 0 self._aifc = 1 # AIFF-C is default
def __del__(self): self.close()
def __enter__(self): return self
def __exit__(self, *args): self.close()
# # User visible methods. # def aiff(self): if self._nframeswritten: raise Error('cannot change parameters after starting to write') self._aifc = 0
def aifc(self): if self._nframeswritten: raise Error('cannot change parameters after starting to write') self._aifc = 1
def setnchannels(self, nchannels): if self._nframeswritten: raise Error('cannot change parameters after starting to write') if nchannels < 1: raise Error('bad # of channels') self._nchannels = nchannels
def getnchannels(self): if not self._nchannels: raise Error('number of channels not set') return self._nchannels
def setsampwidth(self, sampwidth): if self._nframeswritten: raise Error('cannot change parameters after starting to write') if sampwidth < 1 or sampwidth > 4: raise Error('bad sample width') self._sampwidth = sampwidth
def getsampwidth(self): if not self._sampwidth: raise Error('sample width not set') return self._sampwidth
def setframerate(self, framerate): if self._nframeswritten: raise Error('cannot change parameters after starting to write') if framerate <= 0: raise Error('bad frame rate') self._framerate = framerate
def getframerate(self): if not self._framerate: raise Error('frame rate not set') return self._framerate
def setnframes(self, nframes): if self._nframeswritten: raise Error('cannot change parameters after starting to write') self._nframes = nframes
def getnframes(self): return self._nframeswritten
def setcomptype(self, comptype, compname): if self._nframeswritten: raise Error('cannot change parameters after starting to write') if comptype not in (b'NONE', b'ulaw', b'ULAW', b'alaw', b'ALAW', b'G722'): raise Error('unsupported compression type') self._comptype = comptype self._compname = compname
def getcomptype(self): return self._comptype
def getcompname(self): return self._compname
## def setversion(self, version):## if self._nframeswritten:## raise Error, 'cannot change parameters after starting to write'## self._version = version
def setparams(self, params): nchannels, sampwidth, framerate, nframes, comptype, compname = params if self._nframeswritten: raise Error('cannot change parameters after starting to write') if comptype not in (b'NONE', b'ulaw', b'ULAW', b'alaw', b'ALAW', b'G722'): raise Error('unsupported compression type') self.setnchannels(nchannels) self.setsampwidth(sampwidth) self.setframerate(framerate) self.setnframes(nframes) self.setcomptype(comptype, compname)
def getparams(self): if not self._nchannels or not self._sampwidth or not self._framerate: raise Error('not all parameters set') return _aifc_params(self._nchannels, self._sampwidth, self._framerate, self._nframes, self._comptype, self._compname)
def setmark(self, id, pos, name): if id <= 0: raise Error('marker ID must be > 0') if pos < 0: raise Error('marker position must be >= 0') if not isinstance(name, bytes): raise Error('marker name must be bytes') for i in range(len(self._markers)): if id == self._markers[i][0]: self._markers[i] = id, pos, name return self._markers.append((id, pos, name))
def getmark(self, id): for marker in self._markers: if id == marker[0]: return marker raise Error('marker {0!r} does not exist'.format(id))
def getmarkers(self): if len(self._markers) == 0: return None return self._markers
def tell(self): return self._nframeswritten
def writeframesraw(self, data): if not isinstance(data, (bytes, bytearray)): data = memoryview(data).cast('B') self._ensure_header_written(len(data)) nframes = len(data) // (self._sampwidth * self._nchannels) if self._convert: data = self._convert(data) self._file.write(data) self._nframeswritten = self._nframeswritten + nframes self._datawritten = self._datawritten + len(data)
def writeframes(self, data): self.writeframesraw(data) if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten: self._patchheader()
def close(self): if self._file is None: return try: self._ensure_header_written(0) if self._datawritten & 1: # quick pad to even size self._file.write(b'\x00') self._datawritten = self._datawritten + 1 self._writemarkers() if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten or \ self._marklength: self._patchheader() finally: # Prevent ref cycles self._convert = None f = self._file self._file = None f.close()
# # Internal methods. #
def _lin2alaw(self, data): import audioop return audioop.lin2alaw(data, 2)
def _lin2ulaw(self, data): import audioop return audioop.lin2ulaw(data, 2)
def _lin2adpcm(self, data): import audioop if not hasattr(self, '_adpcmstate'): self._adpcmstate = None data, self._adpcmstate = audioop.lin2adpcm(data, 2, self._adpcmstate) return data
def _ensure_header_written(self, datasize): if not self._nframeswritten: if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'): if not self._sampwidth: self._sampwidth = 2 if self._sampwidth != 2: raise Error('sample width must be 2 when compressing ' 'with ulaw/ULAW, alaw/ALAW or G7.22 (ADPCM)') if not self._nchannels: raise Error('# channels not specified') if not self._sampwidth: raise Error('sample width not specified') if not self._framerate: raise Error('sampling rate not specified') self._write_header(datasize)
def _init_compression(self): if self._comptype == b'G722': self._convert = self._lin2adpcm elif self._comptype in (b'ulaw', b'ULAW'): self._convert = self._lin2ulaw elif self._comptype in (b'alaw', b'ALAW'): self._convert = self._lin2alaw
def _write_header(self, initlength): if self._aifc and self._comptype != b'NONE': self._init_compression() self._file.write(b'FORM') if not self._nframes: self._nframes = initlength // (self._nchannels * self._sampwidth) self._datalength = self._nframes * self._nchannels * self._sampwidth if self._datalength & 1: self._datalength = self._datalength + 1 if self._aifc: if self._comptype in (b'ulaw', b'ULAW', b'alaw', b'ALAW'): self._datalength = self._datalength // 2 if self._datalength & 1: self._datalength = self._datalength + 1 elif self._comptype == b'G722': self._datalength = (self._datalength + 3) // 4 if self._datalength & 1: self._datalength = self._datalength + 1 try: self._form_length_pos = self._file.tell() except (AttributeError, OSError): self._form_length_pos = None commlength = self._write_form_length(self._datalength) if self._aifc: self._file.write(b'AIFC') self._file.write(b'FVER') _write_ulong(self._file, 4) _write_ulong(self._file, self._version) else: self._file.write(b'AIFF') self._file.write(b'COMM') _write_ulong(self._file, commlength) _write_short(self._file, self._nchannels) if self._form_length_pos is not None: self._nframes_pos = self._file.tell() _write_ulong(self._file, self._nframes) if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'): _write_short(self._file, 8) else: _write_short(self._file, self._sampwidth * 8) _write_float(self._file, self._framerate) if self._aifc: self._file.write(self._comptype) _write_string(self._file, self._compname) self._file.write(b'SSND') if self._form_length_pos is not None: self._ssnd_length_pos = self._file.tell() _write_ulong(self._file, self._datalength + 8) _write_ulong(self._file, 0) _write_ulong(self._file, 0)
def _write_form_length(self, datalength): if self._aifc: commlength = 18 + 5 + len(self._compname) if commlength & 1: commlength = commlength + 1 verslength = 12 else: commlength = 18 verslength = 0 _write_ulong(self._file, 4 + verslength + self._marklength + \ 8 + commlength + 16 + datalength) return commlength
def _patchheader(self): curpos = self._file.tell() if self._datawritten & 1: datalength = self._datawritten + 1 self._file.write(b'\x00') else: datalength = self._datawritten if datalength == self._datalength and \ self._nframes == self._nframeswritten and \ self._marklength == 0: self._file.seek(curpos, 0) return self._file.seek(self._form_length_pos, 0) dummy = self._write_form_length(datalength) self._file.seek(self._nframes_pos, 0) _write_ulong(self._file, self._nframeswritten) self._file.seek(self._ssnd_length_pos, 0) _write_ulong(self._file, datalength + 8) self._file.seek(curpos, 0) self._nframes = self._nframeswritten self._datalength = datalength
def _writemarkers(self): if len(self._markers) == 0: return self._file.write(b'MARK') length = 2 for marker in self._markers: id, pos, name = marker length = length + len(name) + 1 + 6 if len(name) & 1 == 0: length = length + 1 _write_ulong(self._file, length) self._marklength = length + 8 _write_short(self._file, len(self._markers)) for marker in self._markers: id, pos, name = marker _write_short(self._file, id) _write_ulong(self._file, pos) _write_string(self._file, name)
def open(f, mode=None): if mode is None: if hasattr(f, 'mode'): mode = f.mode else: mode = 'rb' if mode in ('r', 'rb'): return Aifc_read(f) elif mode in ('w', 'wb'): return Aifc_write(f) else: raise Error("mode must be 'r', 'rb', 'w', or 'wb'")
if __name__ == '__main__': import sys if not sys.argv[1:]: sys.argv.append('/usr/demos/data/audio/bach.aiff') fn = sys.argv[1] with open(fn, 'r') as f: print("Reading", fn) print("nchannels =", f.getnchannels()) print("nframes =", f.getnframes()) print("sampwidth =", f.getsampwidth()) print("framerate =", f.getframerate()) print("comptype =", f.getcomptype()) print("compname =", f.getcompname()) if sys.argv[2:]: gn = sys.argv[2] print("Writing", gn) with open(gn, 'w') as g: g.setparams(f.getparams()) while 1: data = f.readframes(1024) if not data: break g.writeframes(data) print("Done.")1234567891011121314151617
import webbrowserimport hashlib
webbrowser.open("https://xkcd.com/353/")
def geohash(latitude, longitude, datedow): '''Compute geohash() using the Munroe algorithm.
>>> geohash(37.421542, -122.085589, b'2005-05-26-10458.68') 37.857713 -122.544543
''' # https://xkcd.com/426/ h = hashlib.md5(datedow, usedforsecurity=False).hexdigest() p, q = [('%f' % float.fromhex('0.' + x)) for x in (h[:16], h[16:32])] print('%d%s %d%s' % (latitude, p[1:], longitude, q[1:]))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709""" ast ~~~
The `ast` module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like and allows modifications of it.
An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as a flag to the `compile()` builtin function or by using the `parse()` function from this module. The result will be a tree of objects whose classes all inherit from `ast.AST`.
A modified abstract syntax tree can be compiled into a Python code object using the built-in `compile()` function.
Additionally various helper functions are provided that make working with the trees simpler. The main intention of the helper functions and this module in general is to provide an easy to use interface for libraries that work tightly with the python syntax (template engines for example).
:copyright: Copyright 2008 by Armin Ronacher. :license: Python License."""import sysfrom _ast import *from contextlib import contextmanager, nullcontextfrom enum import IntEnum, auto
def parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None): """ Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). Pass type_comments=True to get back type comments where the syntax allows. """ flags = PyCF_ONLY_AST if type_comments: flags |= PyCF_TYPE_COMMENTS if isinstance(feature_version, tuple): major, minor = feature_version # Should be a 2-tuple. assert major == 3 feature_version = minor elif feature_version is None: feature_version = -1 # Else it should be an int giving the minor version for 3.x. return compile(source, filename, mode, flags, _feature_version=feature_version)
def literal_eval(node_or_string): """ Evaluate an expression node or a string containing only a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
Caution: A complex expression can overflow the C stack and cause a crash. """ if isinstance(node_or_string, str): node_or_string = parse(node_or_string.lstrip(" \t"), mode='eval') if isinstance(node_or_string, Expression): node_or_string = node_or_string.body def _raise_malformed_node(node): msg = "malformed node or string" if lno := getattr(node, 'lineno', None): msg += f' on line {lno}' raise ValueError(msg + f': {node!r}') def _convert_num(node): if not isinstance(node, Constant) or type(node.value) not in (int, float, complex): _raise_malformed_node(node) return node.value def _convert_signed_num(node): if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)): operand = _convert_num(node.operand) if isinstance(node.op, UAdd): return + operand else: return - operand return _convert_num(node) def _convert(node): if isinstance(node, Constant): return node.value elif isinstance(node, Tuple): return tuple(map(_convert, node.elts)) elif isinstance(node, List): return list(map(_convert, node.elts)) elif isinstance(node, Set): return set(map(_convert, node.elts)) elif (isinstance(node, Call) and isinstance(node.func, Name) and node.func.id == 'set' and node.args == node.keywords == []): return set() elif isinstance(node, Dict): if len(node.keys) != len(node.values): _raise_malformed_node(node) return dict(zip(map(_convert, node.keys), map(_convert, node.values))) elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)): left = _convert_signed_num(node.left) right = _convert_num(node.right) if isinstance(left, (int, float)) and isinstance(right, complex): if isinstance(node.op, Add): return left + right else: return left - right return _convert_signed_num(node) return _convert(node_or_string)
def dump(node, annotate_fields=True, include_attributes=False, *, indent=None): """ Return a formatted dump of the tree in node. This is mainly useful for debugging purposes. If annotate_fields is true (by default), the returned string will show the names and the values for fields. If annotate_fields is false, the result string will be more compact by omitting unambiguous field names. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, include_attributes can be set to true. If indent is a non-negative integer or string, then the tree will be pretty-printed with that indent level. None (the default) selects the single line representation. """ def _format(node, level=0): if indent is not None: level += 1 prefix = '\n' + indent * level sep = ',\n' + indent * level else: prefix = '' sep = ', ' if isinstance(node, AST): cls = type(node) args = [] allsimple = True keywords = annotate_fields for name in node._fields: try: value = getattr(node, name) except AttributeError: keywords = True continue if value is None and getattr(cls, name, ...) is None: keywords = True continue value, simple = _format(value, level) allsimple = allsimple and simple if keywords: args.append('%s=%s' % (name, value)) else: args.append(value) if include_attributes and node._attributes: for name in node._attributes: try: value = getattr(node, name) except AttributeError: continue if value is None and getattr(cls, name, ...) is None: continue value, simple = _format(value, level) allsimple = allsimple and simple args.append('%s=%s' % (name, value)) if allsimple and len(args) <= 3: return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False elif isinstance(node, list): if not node: return '[]', True return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False return repr(node), True
if not isinstance(node, AST): raise TypeError('expected AST, got %r' % node.__class__.__name__) if indent is not None and not isinstance(indent, str): indent = ' ' * indent return _format(node)[0]
def copy_location(new_node, old_node): """ Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*. """ for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset': if attr in old_node._attributes and attr in new_node._attributes: value = getattr(old_node, attr, None) # end_lineno and end_col_offset are optional attributes, and they # should be copied whether the value is None or not. if value is not None or ( hasattr(old_node, attr) and attr.startswith("end_") ): setattr(new_node, attr, value) return new_node
def fix_missing_locations(node): """ When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*. """ def _fix(node, lineno, col_offset, end_lineno, end_col_offset): if 'lineno' in node._attributes: if not hasattr(node, 'lineno'): node.lineno = lineno else: lineno = node.lineno if 'end_lineno' in node._attributes: if getattr(node, 'end_lineno', None) is None: node.end_lineno = end_lineno else: end_lineno = node.end_lineno if 'col_offset' in node._attributes: if not hasattr(node, 'col_offset'): node.col_offset = col_offset else: col_offset = node.col_offset if 'end_col_offset' in node._attributes: if getattr(node, 'end_col_offset', None) is None: node.end_col_offset = end_col_offset else: end_col_offset = node.end_col_offset for child in iter_child_nodes(node): _fix(child, lineno, col_offset, end_lineno, end_col_offset) _fix(node, 1, 0, 1, 0) return node
def increment_lineno(node, n=1): """ Increment the line number and end line number of each node in the tree starting at *node* by *n*. This is useful to "move code" to a different location in a file. """ for child in walk(node): # TypeIgnore is a special case where lineno is not an attribute # but rather a field of the node itself. if isinstance(child, TypeIgnore): child.lineno = getattr(child, 'lineno', 0) + n continue
if 'lineno' in child._attributes: child.lineno = getattr(child, 'lineno', 0) + n if ( "end_lineno" in child._attributes and (end_lineno := getattr(child, "end_lineno", 0)) is not None ): child.end_lineno = end_lineno + n return node
def iter_fields(node): """ Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. """ for field in node._fields: try: yield field, getattr(node, field) except AttributeError: pass
def iter_child_nodes(node): """ Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. """ for name, field in iter_fields(node): if isinstance(field, AST): yield field elif isinstance(field, list): for item in field: if isinstance(item, AST): yield item
def get_docstring(node, clean=True): """ Return the docstring for the given node or None if no docstring can be found. If the node provided does not have docstrings a TypeError will be raised.
If *clean* is `True`, all tabs are expanded to spaces and any whitespace that can be uniformly removed from the second line onwards is removed. """ if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)): raise TypeError("%r can't have docstrings" % node.__class__.__name__) if not(node.body and isinstance(node.body[0], Expr)): return None node = node.body[0].value if isinstance(node, Str): text = node.s elif isinstance(node, Constant) and isinstance(node.value, str): text = node.value else: return None if clean: import inspect text = inspect.cleandoc(text) return text
def _splitlines_no_ff(source): """Split a string into lines ignoring form feed and other chars.
This mimics how the Python parser splits source code. """ idx = 0 lines = [] next_line = '' while idx < len(source): c = source[idx] next_line += c idx += 1 # Keep \r\n together if c == '\r' and idx < len(source) and source[idx] == '\n': next_line += '\n' idx += 1 if c in '\r\n': lines.append(next_line) next_line = ''
if next_line: lines.append(next_line) return lines
def _pad_whitespace(source): r"""Replace all chars except '\f\t' in a line with spaces.""" result = '' for c in source: if c in '\f\t': result += c else: result += ' ' return result
def get_source_segment(source, node, *, padded=False): """Get source code segment of the *source* that generated *node*.
If some location information (`lineno`, `end_lineno`, `col_offset`, or `end_col_offset`) is missing, return None.
If *padded* is `True`, the first line of a multi-line statement will be padded with spaces to match its original position. """ try: if node.end_lineno is None or node.end_col_offset is None: return None lineno = node.lineno - 1 end_lineno = node.end_lineno - 1 col_offset = node.col_offset end_col_offset = node.end_col_offset except AttributeError: return None
lines = _splitlines_no_ff(source) if end_lineno == lineno: return lines[lineno].encode()[col_offset:end_col_offset].decode()
if padded: padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode()) else: padding = ''
first = padding + lines[lineno].encode()[col_offset:].decode() last = lines[end_lineno].encode()[:end_col_offset].decode() lines = lines[lineno+1:end_lineno]
lines.insert(0, first) lines.append(last) return ''.join(lines)
def walk(node): """ Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context. """ from collections import deque todo = deque([node]) while todo: node = todo.popleft() todo.extend(iter_child_nodes(node)) yield node
class NodeVisitor(object): """ A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method.
This class is meant to be subclassed, with the subclass adding visitor methods.
Per default the visitor functions for the nodes are ``'visit_'`` + class name of the node. So a `TryFinally` node visit function would be `visit_TryFinally`. This behavior can be changed by overriding the `visit` method. If no visitor function exists for a node (return value `None`) the `generic_visit` visitor is used instead.
Don't use the `NodeVisitor` if you want to apply changes to nodes during traversing. For this a special visitor exists (`NodeTransformer`) that allows modifications. """
def visit(self, node): """Visit a node.""" method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node)
def generic_visit(self, node): """Called if no explicit visitor function exists for a node.""" for field, value in iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, AST): self.visit(item) elif isinstance(value, AST): self.visit(value)
def visit_Constant(self, node): value = node.value type_name = _const_node_type_names.get(type(value)) if type_name is None: for cls, name in _const_node_type_names.items(): if isinstance(value, cls): type_name = name break if type_name is not None: method = 'visit_' + type_name try: visitor = getattr(self, method) except AttributeError: pass else: import warnings warnings.warn(f"{method} is deprecated; add visit_Constant", DeprecationWarning, 2) return visitor(node) return self.generic_visit(node)
class NodeTransformer(NodeVisitor): """ A :class:`NodeVisitor` subclass that walks the abstract syntax tree and allows modification of nodes.
The `NodeTransformer` will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the visitor method is ``None``, the node will be removed from its location, otherwise it is replaced with the return value. The return value may be the original node in which case no replacement takes place.
Here is an example transformer that rewrites all occurrences of name lookups (``foo``) to ``data['foo']``::
class RewriteName(NodeTransformer):
def visit_Name(self, node): return Subscript( value=Name(id='data', ctx=Load()), slice=Constant(value=node.id), ctx=node.ctx )
Keep in mind that if the node you're operating on has child nodes you must either transform the child nodes yourself or call the :meth:`generic_visit` method for the node first.
For nodes that were part of a collection of statements (that applies to all statement nodes), the visitor may also return a list of nodes rather than just a single node.
Usually you use the transformer like this::
node = YourTransformer().visit(node) """
def generic_visit(self, node): for field, old_value in iter_fields(node): if isinstance(old_value, list): new_values = [] for value in old_value: if isinstance(value, AST): value = self.visit(value) if value is None: continue elif not isinstance(value, AST): new_values.extend(value) continue new_values.append(value) old_value[:] = new_values elif isinstance(old_value, AST): new_node = self.visit(old_value) if new_node is None: delattr(node, field) else: setattr(node, field, new_node) return node
# If the ast module is loaded more than once, only add deprecated methods onceif not hasattr(Constant, 'n'): # The following code is for backward compatibility. # It will be removed in future.
def _getter(self): """Deprecated. Use value instead.""" return self.value
def _setter(self, value): self.value = value
Constant.n = property(_getter, _setter) Constant.s = property(_getter, _setter)
class _ABC(type):
def __init__(cls, *args): cls.__doc__ = """Deprecated AST node class. Use ast.Constant instead"""
def __instancecheck__(cls, inst): if not isinstance(inst, Constant): return False if cls in _const_types: try: value = inst.value except AttributeError: return False else: return ( isinstance(value, _const_types[cls]) and not isinstance(value, _const_types_not.get(cls, ())) ) return type.__instancecheck__(cls, inst)
def _new(cls, *args, **kwargs): for key in kwargs: if key not in cls._fields: # arbitrary keyword arguments are accepted continue pos = cls._fields.index(key) if pos < len(args): raise TypeError(f"{cls.__name__} got multiple values for argument {key!r}") if cls in _const_types: return Constant(*args, **kwargs) return Constant.__new__(cls, *args, **kwargs)
class Num(Constant, metaclass=_ABC): _fields = ('n',) __new__ = _new
class Str(Constant, metaclass=_ABC): _fields = ('s',) __new__ = _new
class Bytes(Constant, metaclass=_ABC): _fields = ('s',) __new__ = _new
class NameConstant(Constant, metaclass=_ABC): __new__ = _new
class Ellipsis(Constant, metaclass=_ABC): _fields = ()
def __new__(cls, *args, **kwargs): if cls is Ellipsis: return Constant(..., *args, **kwargs) return Constant.__new__(cls, *args, **kwargs)
_const_types = { Num: (int, float, complex), Str: (str,), Bytes: (bytes,), NameConstant: (type(None), bool), Ellipsis: (type(...),),}_const_types_not = { Num: (bool,),}
_const_node_type_names = { bool: 'NameConstant', # should be before int type(None): 'NameConstant', int: 'Num', float: 'Num', complex: 'Num', str: 'Str', bytes: 'Bytes', type(...): 'Ellipsis',}
class slice(AST): """Deprecated AST node class."""
class Index(slice): """Deprecated AST node class. Use the index value directly instead.""" def __new__(cls, value, **kwargs): return value
class ExtSlice(slice): """Deprecated AST node class. Use ast.Tuple instead.""" def __new__(cls, dims=(), **kwargs): return Tuple(list(dims), Load(), **kwargs)
# If the ast module is loaded more than once, only add deprecated methods onceif not hasattr(Tuple, 'dims'): # The following code is for backward compatibility. # It will be removed in future.
def _dims_getter(self): """Deprecated. Use elts instead.""" return self.elts
def _dims_setter(self, value): self.elts = value
Tuple.dims = property(_dims_getter, _dims_setter)
class Suite(mod): """Deprecated AST node class. Unused in Python 3."""
class AugLoad(expr_context): """Deprecated AST node class. Unused in Python 3."""
class AugStore(expr_context): """Deprecated AST node class. Unused in Python 3."""
class Param(expr_context): """Deprecated AST node class. Unused in Python 3."""
# Large float and imaginary literals get turned into infinities in the AST.# We unparse those infinities to INFSTR._INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
class _Precedence(IntEnum): """Precedence table that originated from python grammar."""
TUPLE = auto() YIELD = auto() # 'yield', 'yield from' TEST = auto() # 'if'-'else', 'lambda' OR = auto() # 'or' AND = auto() # 'and' NOT = auto() # 'not' CMP = auto() # '<', '>', '==', '>=', '<=', '!=', # 'in', 'not in', 'is', 'is not' EXPR = auto() BOR = EXPR # '|' BXOR = auto() # '^' BAND = auto() # '&' SHIFT = auto() # '<<', '>>' ARITH = auto() # '+', '-' TERM = auto() # '*', '@', '/', '%', '//' FACTOR = auto() # unary '+', '-', '~' POWER = auto() # '**' AWAIT = auto() # 'await' ATOM = auto()
def next(self): try: return self.__class__(self + 1) except ValueError: return self
_SINGLE_QUOTES = ("'", '"')_MULTI_QUOTES = ('"""', "'''")_ALL_QUOTES = (*_SINGLE_QUOTES, *_MULTI_QUOTES)
class _Unparser(NodeVisitor): """Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded."""
def __init__(self, *, _avoid_backslashes=False): self._source = [] self._buffer = [] self._precedences = {} self._type_ignores = {} self._indent = 0 self._avoid_backslashes = _avoid_backslashes
def interleave(self, inter, f, seq): """Call f on each item in seq, calling inter() in between.""" seq = iter(seq) try: f(next(seq)) except StopIteration: pass else: for x in seq: inter() f(x)
def items_view(self, traverser, items): """Traverse and separate the given *items* with a comma and append it to the buffer. If *items* is a single item sequence, a trailing comma will be added.""" if len(items) == 1: traverser(items[0]) self.write(",") else: self.interleave(lambda: self.write(", "), traverser, items)
def maybe_newline(self): """Adds a newline if it isn't the start of generated source""" if self._source: self.write("\n")
def fill(self, text=""): """Indent a piece of text and append it, according to the current indentation level""" self.maybe_newline() self.write(" " * self._indent + text)
def write(self, text): """Append a piece of text""" self._source.append(text)
def buffer_writer(self, text): self._buffer.append(text)
@property def buffer(self): value = "".join(self._buffer) self._buffer.clear() return value
@contextmanager def block(self, *, extra = None): """A context manager for preparing the source for blocks. It adds the character':', increases the indentation on enter and decreases the indentation on exit. If *extra* is given, it will be directly appended after the colon character. """ self.write(":") if extra: self.write(extra) self._indent += 1 yield self._indent -= 1
@contextmanager def delimit(self, start, end): """A context manager for preparing the source for expressions. It adds *start* to the buffer and enters, after exit it adds *end*."""
self.write(start) yield self.write(end)
def delimit_if(self, start, end, condition): if condition: return self.delimit(start, end) else: return nullcontext()
def require_parens(self, precedence, node): """Shortcut to adding precedence related parens""" return self.delimit_if("(", ")", self.get_precedence(node) > precedence)
def get_precedence(self, node): return self._precedences.get(node, _Precedence.TEST)
def set_precedence(self, precedence, *nodes): for node in nodes: self._precedences[node] = precedence
def get_raw_docstring(self, node): """If a docstring node is found in the body of the *node* parameter, return that docstring node, None otherwise.
Logic mirrored from ``_PyAST_GetDocString``.""" if not isinstance( node, (AsyncFunctionDef, FunctionDef, ClassDef, Module) ) or len(node.body) < 1: return None node = node.body[0] if not isinstance(node, Expr): return None node = node.value if isinstance(node, Constant) and isinstance(node.value, str): return node
def get_type_comment(self, node): comment = self._type_ignores.get(node.lineno) or node.type_comment if comment is not None: return f" # type: {comment}"
def traverse(self, node): if isinstance(node, list): for item in node: self.traverse(item) else: super().visit(node)
# Note: as visit() resets the output text, do NOT rely on # NodeVisitor.generic_visit to handle any nodes (as it calls back in to # the subclass visit() method, which resets self._source to an empty list) def visit(self, node): """Outputs a source code string that, if converted back to an ast (using ast.parse) will generate an AST equivalent to *node*""" self._source = [] self.traverse(node) return "".join(self._source)
def _write_docstring_and_traverse_body(self, node): if (docstring := self.get_raw_docstring(node)): self._write_docstring(docstring) self.traverse(node.body[1:]) else: self.traverse(node.body)
def visit_Module(self, node): self._type_ignores = { ignore.lineno: f"ignore{ignore.tag}" for ignore in node.type_ignores } self._write_docstring_and_traverse_body(node) self._type_ignores.clear()
def visit_FunctionType(self, node): with self.delimit("(", ")"): self.interleave( lambda: self.write(", "), self.traverse, node.argtypes )
self.write(" -> ") self.traverse(node.returns)
def visit_Expr(self, node): self.fill() self.set_precedence(_Precedence.YIELD, node.value) self.traverse(node.value)
def visit_NamedExpr(self, node): with self.require_parens(_Precedence.TUPLE, node): self.set_precedence(_Precedence.ATOM, node.target, node.value) self.traverse(node.target) self.write(" := ") self.traverse(node.value)
def visit_Import(self, node): self.fill("import ") self.interleave(lambda: self.write(", "), self.traverse, node.names)
def visit_ImportFrom(self, node): self.fill("from ") self.write("." * (node.level or 0)) if node.module: self.write(node.module) self.write(" import ") self.interleave(lambda: self.write(", "), self.traverse, node.names)
def visit_Assign(self, node): self.fill() for target in node.targets: self.traverse(target) self.write(" = ") self.traverse(node.value) if type_comment := self.get_type_comment(node): self.write(type_comment)
def visit_AugAssign(self, node): self.fill() self.traverse(node.target) self.write(" " + self.binop[node.op.__class__.__name__] + "= ") self.traverse(node.value)
def visit_AnnAssign(self, node): self.fill() with self.delimit_if("(", ")", not node.simple and isinstance(node.target, Name)): self.traverse(node.target) self.write(": ") self.traverse(node.annotation) if node.value: self.write(" = ") self.traverse(node.value)
def visit_Return(self, node): self.fill("return") if node.value: self.write(" ") self.traverse(node.value)
def visit_Pass(self, node): self.fill("pass")
def visit_Break(self, node): self.fill("break")
def visit_Continue(self, node): self.fill("continue")
def visit_Delete(self, node): self.fill("del ") self.interleave(lambda: self.write(", "), self.traverse, node.targets)
def visit_Assert(self, node): self.fill("assert ") self.traverse(node.test) if node.msg: self.write(", ") self.traverse(node.msg)
def visit_Global(self, node): self.fill("global ") self.interleave(lambda: self.write(", "), self.write, node.names)
def visit_Nonlocal(self, node): self.fill("nonlocal ") self.interleave(lambda: self.write(", "), self.write, node.names)
def visit_Await(self, node): with self.require_parens(_Precedence.AWAIT, node): self.write("await") if node.value: self.write(" ") self.set_precedence(_Precedence.ATOM, node.value) self.traverse(node.value)
def visit_Yield(self, node): with self.require_parens(_Precedence.YIELD, node): self.write("yield") if node.value: self.write(" ") self.set_precedence(_Precedence.ATOM, node.value) self.traverse(node.value)
def visit_YieldFrom(self, node): with self.require_parens(_Precedence.YIELD, node): self.write("yield from ") if not node.value: raise ValueError("Node can't be used without a value attribute.") self.set_precedence(_Precedence.ATOM, node.value) self.traverse(node.value)
def visit_Raise(self, node): self.fill("raise") if not node.exc: if node.cause: raise ValueError(f"Node can't use cause without an exception.") return self.write(" ") self.traverse(node.exc) if node.cause: self.write(" from ") self.traverse(node.cause)
def visit_Try(self, node): self.fill("try") with self.block(): self.traverse(node.body) for ex in node.handlers: self.traverse(ex) if node.orelse: self.fill("else") with self.block(): self.traverse(node.orelse) if node.finalbody: self.fill("finally") with self.block(): self.traverse(node.finalbody)
def visit_ExceptHandler(self, node): self.fill("except") if node.type: self.write(" ") self.traverse(node.type) if node.name: self.write(" as ") self.write(node.name) with self.block(): self.traverse(node.body)
def visit_ClassDef(self, node): self.maybe_newline() for deco in node.decorator_list: self.fill("@") self.traverse(deco) self.fill("class " + node.name) with self.delimit_if("(", ")", condition = node.bases or node.keywords): comma = False for e in node.bases: if comma: self.write(", ") else: comma = True self.traverse(e) for e in node.keywords: if comma: self.write(", ") else: comma = True self.traverse(e)
with self.block(): self._write_docstring_and_traverse_body(node)
def visit_FunctionDef(self, node): self._function_helper(node, "def")
def visit_AsyncFunctionDef(self, node): self._function_helper(node, "async def")
def _function_helper(self, node, fill_suffix): self.maybe_newline() for deco in node.decorator_list: self.fill("@") self.traverse(deco) def_str = fill_suffix + " " + node.name self.fill(def_str) with self.delimit("(", ")"): self.traverse(node.args) if node.returns: self.write(" -> ") self.traverse(node.returns) with self.block(extra=self.get_type_comment(node)): self._write_docstring_and_traverse_body(node)
def visit_For(self, node): self._for_helper("for ", node)
def visit_AsyncFor(self, node): self._for_helper("async for ", node)
def _for_helper(self, fill, node): self.fill(fill) self.traverse(node.target) self.write(" in ") self.traverse(node.iter) with self.block(extra=self.get_type_comment(node)): self.traverse(node.body) if node.orelse: self.fill("else") with self.block(): self.traverse(node.orelse)
def visit_If(self, node): self.fill("if ") self.traverse(node.test) with self.block(): self.traverse(node.body) # collapse nested ifs into equivalent elifs. while node.orelse and len(node.orelse) == 1 and isinstance(node.orelse[0], If): node = node.orelse[0] self.fill("elif ") self.traverse(node.test) with self.block(): self.traverse(node.body) # final else if node.orelse: self.fill("else") with self.block(): self.traverse(node.orelse)
def visit_While(self, node): self.fill("while ") self.traverse(node.test) with self.block(): self.traverse(node.body) if node.orelse: self.fill("else") with self.block(): self.traverse(node.orelse)
def visit_With(self, node): self.fill("with ") self.interleave(lambda: self.write(", "), self.traverse, node.items) with self.block(extra=self.get_type_comment(node)): self.traverse(node.body)
def visit_AsyncWith(self, node): self.fill("async with ") self.interleave(lambda: self.write(", "), self.traverse, node.items) with self.block(extra=self.get_type_comment(node)): self.traverse(node.body)
def _str_literal_helper( self, string, *, quote_types=_ALL_QUOTES, escape_special_whitespace=False ): """Helper for writing string literals, minimizing escapes. Returns the tuple (string literal to write, possible quote types). """ def escape_char(c): # \n and \t are non-printable, but we only escape them if # escape_special_whitespace is True if not escape_special_whitespace and c in "\n\t": return c # Always escape backslashes and other non-printable characters if c == "\\" or not c.isprintable(): return c.encode("unicode_escape").decode("ascii") return c
escaped_string = "".join(map(escape_char, string)) possible_quotes = quote_types if "\n" in escaped_string: possible_quotes = [q for q in possible_quotes if q in _MULTI_QUOTES] possible_quotes = [q for q in possible_quotes if q not in escaped_string] if not possible_quotes: # If there aren't any possible_quotes, fallback to using repr # on the original string. Try to use a quote from quote_types, # e.g., so that we use triple quotes for docstrings. string = repr(string) quote = next((q for q in quote_types if string[0] in q), string[0]) return string[1:-1], [quote] if escaped_string: # Sort so that we prefer '''"''' over """\"""" possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1]) # If we're using triple quotes and we'd need to escape a final # quote, escape it if possible_quotes[0][0] == escaped_string[-1]: assert len(possible_quotes[0]) == 3 escaped_string = escaped_string[:-1] + "\\" + escaped_string[-1] return escaped_string, possible_quotes
def _write_str_avoiding_backslashes(self, string, *, quote_types=_ALL_QUOTES): """Write string literal value with a best effort attempt to avoid backslashes.""" string, quote_types = self._str_literal_helper(string, quote_types=quote_types) quote_type = quote_types[0] self.write(f"{quote_type}{string}{quote_type}")
def visit_JoinedStr(self, node): self.write("f") if self._avoid_backslashes: self._fstring_JoinedStr(node, self.buffer_writer) self._write_str_avoiding_backslashes(self.buffer) return
# If we don't need to avoid backslashes globally (i.e., we only need # to avoid them inside FormattedValues), it's cosmetically preferred # to use escaped whitespace. That is, it's preferred to use backslashes # for cases like: f"{x}\n". To accomplish this, we keep track of what # in our buffer corresponds to FormattedValues and what corresponds to # Constant parts of the f-string, and allow escapes accordingly. buffer = [] for value in node.values: meth = getattr(self, "_fstring_" + type(value).__name__) meth(value, self.buffer_writer) buffer.append((self.buffer, isinstance(value, Constant))) new_buffer = [] quote_types = _ALL_QUOTES for value, is_constant in buffer: # Repeatedly narrow down the list of possible quote_types value, quote_types = self._str_literal_helper( value, quote_types=quote_types, escape_special_whitespace=is_constant ) new_buffer.append(value) value = "".join(new_buffer) quote_type = quote_types[0] self.write(f"{quote_type}{value}{quote_type}")
def visit_FormattedValue(self, node): self.write("f") self._fstring_FormattedValue(node, self.buffer_writer) self._write_str_avoiding_backslashes(self.buffer)
def _fstring_JoinedStr(self, node, write): for value in node.values: meth = getattr(self, "_fstring_" + type(value).__name__) meth(value, write)
def _fstring_Constant(self, node, write): if not isinstance(node.value, str): raise ValueError("Constants inside JoinedStr should be a string.") value = node.value.replace("{", "{{").replace("}", "}}") write(value)
def _fstring_FormattedValue(self, node, write): write("{") unparser = type(self)(_avoid_backslashes=True) unparser.set_precedence(_Precedence.TEST.next(), node.value) expr = unparser.visit(node.value) if expr.startswith("{"): write(" ") # Separate pair of opening brackets as "{ {" if "\\" in expr: raise ValueError("Unable to avoid backslash in f-string expression part") write(expr) if node.conversion != -1: conversion = chr(node.conversion) if conversion not in "sra": raise ValueError("Unknown f-string conversion.") write(f"!{conversion}") if node.format_spec: write(":") meth = getattr(self, "_fstring_" + type(node.format_spec).__name__) meth(node.format_spec, write) write("}")
def visit_Name(self, node): self.write(node.id)
def _write_docstring(self, node): self.fill() if node.kind == "u": self.write("u") self._write_str_avoiding_backslashes(node.value, quote_types=_MULTI_QUOTES)
def _write_constant(self, value): if isinstance(value, (float, complex)): # Substitute overflowing decimal literal for AST infinities, # and inf - inf for NaNs. self.write( repr(value) .replace("inf", _INFSTR) .replace("nan", f"({_INFSTR}-{_INFSTR})") ) elif self._avoid_backslashes and isinstance(value, str): self._write_str_avoiding_backslashes(value) else: self.write(repr(value))
def visit_Constant(self, node): value = node.value if isinstance(value, tuple): with self.delimit("(", ")"): self.items_view(self._write_constant, value) elif value is ...: self.write("...") else: if node.kind == "u": self.write("u") self._write_constant(node.value)
def visit_List(self, node): with self.delimit("[", "]"): self.interleave(lambda: self.write(", "), self.traverse, node.elts)
def visit_ListComp(self, node): with self.delimit("[", "]"): self.traverse(node.elt) for gen in node.generators: self.traverse(gen)
def visit_GeneratorExp(self, node): with self.delimit("(", ")"): self.traverse(node.elt) for gen in node.generators: self.traverse(gen)
def visit_SetComp(self, node): with self.delimit("{", "}"): self.traverse(node.elt) for gen in node.generators: self.traverse(gen)
def visit_DictComp(self, node): with self.delimit("{", "}"): self.traverse(node.key) self.write(": ") self.traverse(node.value) for gen in node.generators: self.traverse(gen)
def visit_comprehension(self, node): if node.is_async: self.write(" async for ") else: self.write(" for ") self.set_precedence(_Precedence.TUPLE, node.target) self.traverse(node.target) self.write(" in ") self.set_precedence(_Precedence.TEST.next(), node.iter, *node.ifs) self.traverse(node.iter) for if_clause in node.ifs: self.write(" if ") self.traverse(if_clause)
def visit_IfExp(self, node): with self.require_parens(_Precedence.TEST, node): self.set_precedence(_Precedence.TEST.next(), node.body, node.test) self.traverse(node.body) self.write(" if ") self.traverse(node.test) self.write(" else ") self.set_precedence(_Precedence.TEST, node.orelse) self.traverse(node.orelse)
def visit_Set(self, node): if node.elts: with self.delimit("{", "}"): self.interleave(lambda: self.write(", "), self.traverse, node.elts) else: # `{}` would be interpreted as a dictionary literal, and # `set` might be shadowed. Thus: self.write('{*()}')
def visit_Dict(self, node): def write_key_value_pair(k, v): self.traverse(k) self.write(": ") self.traverse(v)
def write_item(item): k, v = item if k is None: # for dictionary unpacking operator in dicts {**{'y': 2}} # see PEP 448 for details self.write("**") self.set_precedence(_Precedence.EXPR, v) self.traverse(v) else: write_key_value_pair(k, v)
with self.delimit("{", "}"): self.interleave( lambda: self.write(", "), write_item, zip(node.keys, node.values) )
def visit_Tuple(self, node): with self.delimit("(", ")"): self.items_view(self.traverse, node.elts)
unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"} unop_precedence = { "not": _Precedence.NOT, "~": _Precedence.FACTOR, "+": _Precedence.FACTOR, "-": _Precedence.FACTOR, }
def visit_UnaryOp(self, node): operator = self.unop[node.op.__class__.__name__] operator_precedence = self.unop_precedence[operator] with self.require_parens(operator_precedence, node): self.write(operator) # factor prefixes (+, -, ~) shouldn't be seperated # from the value they belong, (e.g: +1 instead of + 1) if operator_precedence is not _Precedence.FACTOR: self.write(" ") self.set_precedence(operator_precedence, node.operand) self.traverse(node.operand)
binop = { "Add": "+", "Sub": "-", "Mult": "*", "MatMult": "@", "Div": "/", "Mod": "%", "LShift": "<<", "RShift": ">>", "BitOr": "|", "BitXor": "^", "BitAnd": "&", "FloorDiv": "//", "Pow": "**", }
binop_precedence = { "+": _Precedence.ARITH, "-": _Precedence.ARITH, "*": _Precedence.TERM, "@": _Precedence.TERM, "/": _Precedence.TERM, "%": _Precedence.TERM, "<<": _Precedence.SHIFT, ">>": _Precedence.SHIFT, "|": _Precedence.BOR, "^": _Precedence.BXOR, "&": _Precedence.BAND, "//": _Precedence.TERM, "**": _Precedence.POWER, }
binop_rassoc = frozenset(("**",)) def visit_BinOp(self, node): operator = self.binop[node.op.__class__.__name__] operator_precedence = self.binop_precedence[operator] with self.require_parens(operator_precedence, node): if operator in self.binop_rassoc: left_precedence = operator_precedence.next() right_precedence = operator_precedence else: left_precedence = operator_precedence right_precedence = operator_precedence.next()
self.set_precedence(left_precedence, node.left) self.traverse(node.left) self.write(f" {operator} ") self.set_precedence(right_precedence, node.right) self.traverse(node.right)
cmpops = { "Eq": "==", "NotEq": "!=", "Lt": "<", "LtE": "<=", "Gt": ">", "GtE": ">=", "Is": "is", "IsNot": "is not", "In": "in", "NotIn": "not in", }
def visit_Compare(self, node): with self.require_parens(_Precedence.CMP, node): self.set_precedence(_Precedence.CMP.next(), node.left, *node.comparators) self.traverse(node.left) for o, e in zip(node.ops, node.comparators): self.write(" " + self.cmpops[o.__class__.__name__] + " ") self.traverse(e)
boolops = {"And": "and", "Or": "or"} boolop_precedence = {"and": _Precedence.AND, "or": _Precedence.OR}
def visit_BoolOp(self, node): operator = self.boolops[node.op.__class__.__name__] operator_precedence = self.boolop_precedence[operator]
def increasing_level_traverse(node): nonlocal operator_precedence operator_precedence = operator_precedence.next() self.set_precedence(operator_precedence, node) self.traverse(node)
with self.require_parens(operator_precedence, node): s = f" {operator} " self.interleave(lambda: self.write(s), increasing_level_traverse, node.values)
def visit_Attribute(self, node): self.set_precedence(_Precedence.ATOM, node.value) self.traverse(node.value) # Special case: 3.__abs__() is a syntax error, so if node.value # is an integer literal then we need to either parenthesize # it or add an extra space to get 3 .__abs__(). if isinstance(node.value, Constant) and isinstance(node.value.value, int): self.write(" ") self.write(".") self.write(node.attr)
def visit_Call(self, node): self.set_precedence(_Precedence.ATOM, node.func) self.traverse(node.func) with self.delimit("(", ")"): comma = False for e in node.args: if comma: self.write(", ") else: comma = True self.traverse(e) for e in node.keywords: if comma: self.write(", ") else: comma = True self.traverse(e)
def visit_Subscript(self, node): def is_simple_tuple(slice_value): # when unparsing a non-empty tuple, the parentheses can be safely # omitted if there aren't any elements that explicitly requires # parentheses (such as starred expressions). return ( isinstance(slice_value, Tuple) and slice_value.elts and not any(isinstance(elt, Starred) for elt in slice_value.elts) )
self.set_precedence(_Precedence.ATOM, node.value) self.traverse(node.value) with self.delimit("[", "]"): if is_simple_tuple(node.slice): self.items_view(self.traverse, node.slice.elts) else: self.traverse(node.slice)
def visit_Starred(self, node): self.write("*") self.set_precedence(_Precedence.EXPR, node.value) self.traverse(node.value)
def visit_Ellipsis(self, node): self.write("...")
def visit_Slice(self, node): if node.lower: self.traverse(node.lower) self.write(":") if node.upper: self.traverse(node.upper) if node.step: self.write(":") self.traverse(node.step)
def visit_Match(self, node): self.fill("match ") self.traverse(node.subject) with self.block(): for case in node.cases: self.traverse(case)
def visit_arg(self, node): self.write(node.arg) if node.annotation: self.write(": ") self.traverse(node.annotation)
def visit_arguments(self, node): first = True # normal arguments all_args = node.posonlyargs + node.args defaults = [None] * (len(all_args) - len(node.defaults)) + node.defaults for index, elements in enumerate(zip(all_args, defaults), 1): a, d = elements if first: first = False else: self.write(", ") self.traverse(a) if d: self.write("=") self.traverse(d) if index == len(node.posonlyargs): self.write(", /")
# varargs, or bare '*' if no varargs but keyword-only arguments present if node.vararg or node.kwonlyargs: if first: first = False else: self.write(", ") self.write("*") if node.vararg: self.write(node.vararg.arg) if node.vararg.annotation: self.write(": ") self.traverse(node.vararg.annotation)
# keyword-only arguments if node.kwonlyargs: for a, d in zip(node.kwonlyargs, node.kw_defaults): self.write(", ") self.traverse(a) if d: self.write("=") self.traverse(d)
# kwargs if node.kwarg: if first: first = False else: self.write(", ") self.write("**" + node.kwarg.arg) if node.kwarg.annotation: self.write(": ") self.traverse(node.kwarg.annotation)
def visit_keyword(self, node): if node.arg is None: self.write("**") else: self.write(node.arg) self.write("=") self.traverse(node.value)
def visit_Lambda(self, node): with self.require_parens(_Precedence.TEST, node): self.write("lambda ") self.traverse(node.args) self.write(": ") self.set_precedence(_Precedence.TEST, node.body) self.traverse(node.body)
def visit_alias(self, node): self.write(node.name) if node.asname: self.write(" as " + node.asname)
def visit_withitem(self, node): self.traverse(node.context_expr) if node.optional_vars: self.write(" as ") self.traverse(node.optional_vars)
def visit_match_case(self, node): self.fill("case ") self.traverse(node.pattern) if node.guard: self.write(" if ") self.traverse(node.guard) with self.block(): self.traverse(node.body)
def visit_MatchValue(self, node): self.traverse(node.value)
def visit_MatchSingleton(self, node): self._write_constant(node.value)
def visit_MatchSequence(self, node): with self.delimit("[", "]"): self.interleave( lambda: self.write(", "), self.traverse, node.patterns )
def visit_MatchStar(self, node): name = node.name if name is None: name = "_" self.write(f"*{name}")
def visit_MatchMapping(self, node): def write_key_pattern_pair(pair): k, p = pair self.traverse(k) self.write(": ") self.traverse(p)
with self.delimit("{", "}"): keys = node.keys self.interleave( lambda: self.write(", "), write_key_pattern_pair, zip(keys, node.patterns, strict=True), ) rest = node.rest if rest is not None: if keys: self.write(", ") self.write(f"**{rest}")
def visit_MatchClass(self, node): self.set_precedence(_Precedence.ATOM, node.cls) self.traverse(node.cls) with self.delimit("(", ")"): patterns = node.patterns self.interleave( lambda: self.write(", "), self.traverse, patterns ) attrs = node.kwd_attrs if attrs: def write_attr_pattern(pair): attr, pattern = pair self.write(f"{attr}=") self.traverse(pattern)
if patterns: self.write(", ") self.interleave( lambda: self.write(", "), write_attr_pattern, zip(attrs, node.kwd_patterns, strict=True), )
def visit_MatchAs(self, node): name = node.name pattern = node.pattern if name is None: self.write("_") elif pattern is None: self.write(node.name) else: with self.require_parens(_Precedence.TEST, node): self.set_precedence(_Precedence.BOR, node.pattern) self.traverse(node.pattern) self.write(f" as {node.name}")
def visit_MatchOr(self, node): with self.require_parens(_Precedence.BOR, node): self.set_precedence(_Precedence.BOR.next(), *node.patterns) self.interleave(lambda: self.write(" | "), self.traverse, node.patterns)
def unparse(ast_obj): unparser = _Unparser() return unparser.visit(ast_obj)
def main(): import argparse
parser = argparse.ArgumentParser(prog='python -m ast') parser.add_argument('infile', type=argparse.FileType(mode='rb'), nargs='?', default='-', help='the file to parse; defaults to stdin') parser.add_argument('-m', '--mode', default='exec', choices=('exec', 'single', 'eval', 'func_type'), help='specify what kind of code must be parsed') parser.add_argument('--no-type-comments', default=True, action='store_false', help="don't add information about type comments") parser.add_argument('-a', '--include-attributes', action='store_true', help='include attributes such as line numbers and ' 'column offsets') parser.add_argument('-i', '--indent', type=int, default=3, help='indentation of nodes (number of spaces)') args = parser.parse_args()
with args.infile as infile: source = infile.read() tree = parse(source, args.infile.name, args.mode, type_comments=args.no_type_comments) print(dump(tree, include_attributes=args.include_attributes, indent=args.indent))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315# -*- Mode: Python; tab-width: 4 -*-# Id: asynchat.py,v 2.26 2000/09/07 22:29:26 rushing Exp# Author: Sam Rushing <rushing@nightmare.com>
# ======================================================================# Copyright 1996 by Sam Rushing## All Rights Reserved## Permission to use, copy, modify, and distribute this software and# its documentation for any purpose and without fee is hereby# granted, provided that the above copyright notice appear in all# copies and that both that copyright notice and this permission# notice appear in supporting documentation, and that the name of Sam# Rushing not be used in advertising or publicity pertaining to# distribution of the software without specific, written prior# permission.## SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN# NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.# ======================================================================
r"""A class supporting chat-style (command/response) protocols.
This class adds support for 'chat' style protocols - where one sidesends a 'command', and the other sends a response (examples would bethe common internet protocols - smtp, nntp, ftp, etc..).
The handle_read() method looks at the input stream for the current'terminator' (usually '\r\n' for single-line responses, '\r\n.\r\n'for multi-line output), calling self.found_terminator() on itsreceipt.
for example:Say you build an async nntp client using this class. At the startof the connection, you'll have self.terminator set to '\r\n', inorder to process the single-line greeting. Just before issuing a'LIST' command you'll set it to '\r\n.\r\n'. The output of the LISTcommand will be accumulated (using your own 'collect_incoming_data'method) up to the terminator, and then control will be returned toyou - by calling your self.found_terminator() method."""import asyncorefrom collections import deque
from warnings import warnwarn( 'The asynchat module is deprecated and will be removed in Python 3.12. ' 'The recommended replacement is asyncio', DeprecationWarning, stacklevel=2)
class async_chat(asyncore.dispatcher): """This is an abstract class. You must derive from this class, and add the two methods collect_incoming_data() and found_terminator()"""
# these are overridable defaults
ac_in_buffer_size = 65536 ac_out_buffer_size = 65536
# we don't want to enable the use of encoding by default, because that is a # sign of an application bug that we don't want to pass silently
use_encoding = 0 encoding = 'latin-1'
def __init__(self, sock=None, map=None): # for string terminator matching self.ac_in_buffer = b''
# we use a list here rather than io.BytesIO for a few reasons... # del lst[:] is faster than bio.truncate(0) # lst = [] is faster than bio.truncate(0) self.incoming = []
# we toss the use of the "simple producer" and replace it with # a pure deque, which the original fifo was a wrapping of self.producer_fifo = deque() asyncore.dispatcher.__init__(self, sock, map)
def collect_incoming_data(self, data): raise NotImplementedError("must be implemented in subclass")
def _collect_incoming_data(self, data): self.incoming.append(data)
def _get_data(self): d = b''.join(self.incoming) del self.incoming[:] return d
def found_terminator(self): raise NotImplementedError("must be implemented in subclass")
def set_terminator(self, term): """Set the input delimiter.
Can be a fixed string of any length, an integer, or None. """ if isinstance(term, str) and self.use_encoding: term = bytes(term, self.encoding) elif isinstance(term, int) and term < 0: raise ValueError('the number of received bytes must be positive') self.terminator = term
def get_terminator(self): return self.terminator
# grab some more data from the socket, # throw it to the collector method, # check for the terminator, # if found, transition to the next state.
def handle_read(self):
try: data = self.recv(self.ac_in_buffer_size) except BlockingIOError: return except OSError: self.handle_error() return
if isinstance(data, str) and self.use_encoding: data = bytes(str, self.encoding) self.ac_in_buffer = self.ac_in_buffer + data
# Continue to search for self.terminator in self.ac_in_buffer, # while calling self.collect_incoming_data. The while loop # is necessary because we might read several data+terminator # combos with a single recv(4096).
while self.ac_in_buffer: lb = len(self.ac_in_buffer) terminator = self.get_terminator() if not terminator: # no terminator, collect it all self.collect_incoming_data(self.ac_in_buffer) self.ac_in_buffer = b'' elif isinstance(terminator, int): # numeric terminator n = terminator if lb < n: self.collect_incoming_data(self.ac_in_buffer) self.ac_in_buffer = b'' self.terminator = self.terminator - lb else: self.collect_incoming_data(self.ac_in_buffer[:n]) self.ac_in_buffer = self.ac_in_buffer[n:] self.terminator = 0 self.found_terminator() else: # 3 cases: # 1) end of buffer matches terminator exactly: # collect data, transition # 2) end of buffer matches some prefix: # collect data to the prefix # 3) end of buffer does not match any prefix: # collect data terminator_len = len(terminator) index = self.ac_in_buffer.find(terminator) if index != -1: # we found the terminator if index > 0: # don't bother reporting the empty string # (source of subtle bugs) self.collect_incoming_data(self.ac_in_buffer[:index]) self.ac_in_buffer = self.ac_in_buffer[index+terminator_len:] # This does the Right Thing if the terminator # is changed here. self.found_terminator() else: # check for a prefix of the terminator index = find_prefix_at_end(self.ac_in_buffer, terminator) if index: if index != lb: # we found a prefix, collect up to the prefix self.collect_incoming_data(self.ac_in_buffer[:-index]) self.ac_in_buffer = self.ac_in_buffer[-index:] break else: # no prefix, collect it all self.collect_incoming_data(self.ac_in_buffer) self.ac_in_buffer = b''
def handle_write(self): self.initiate_send()
def handle_close(self): self.close()
def push(self, data): if not isinstance(data, (bytes, bytearray, memoryview)): raise TypeError('data argument must be byte-ish (%r)', type(data)) sabs = self.ac_out_buffer_size if len(data) > sabs: for i in range(0, len(data), sabs): self.producer_fifo.append(data[i:i+sabs]) else: self.producer_fifo.append(data) self.initiate_send()
def push_with_producer(self, producer): self.producer_fifo.append(producer) self.initiate_send()
def readable(self): "predicate for inclusion in the readable for select()" # cannot use the old predicate, it violates the claim of the # set_terminator method.
# return (len(self.ac_in_buffer) <= self.ac_in_buffer_size) return 1
def writable(self): "predicate for inclusion in the writable for select()" return self.producer_fifo or (not self.connected)
def close_when_done(self): "automatically close this channel once the outgoing queue is empty" self.producer_fifo.append(None)
def initiate_send(self): while self.producer_fifo and self.connected: first = self.producer_fifo[0] # handle empty string/buffer or None entry if not first: del self.producer_fifo[0] if first is None: self.handle_close() return
# handle classic producer behavior obs = self.ac_out_buffer_size try: data = first[:obs] except TypeError: data = first.more() if data: self.producer_fifo.appendleft(data) else: del self.producer_fifo[0] continue
if isinstance(data, str) and self.use_encoding: data = bytes(data, self.encoding)
# send the data try: num_sent = self.send(data) except OSError: self.handle_error() return
if num_sent: if num_sent < len(data) or obs < len(first): self.producer_fifo[0] = first[num_sent:] else: del self.producer_fifo[0] # we tried to send some actual data return
def discard_buffers(self): # Emergencies only! self.ac_in_buffer = b'' del self.incoming[:] self.producer_fifo.clear()
class simple_producer:
def __init__(self, data, buffer_size=512): self.data = data self.buffer_size = buffer_size
def more(self): if len(self.data) > self.buffer_size: result = self.data[:self.buffer_size] self.data = self.data[self.buffer_size:] return result else: result = self.data self.data = b'' return result
# Given 'haystack', see if any prefix of 'needle' is at its end. This# assumes an exact match has already been checked. Return the number of# characters matched.# for example:# f_p_a_e("qwerty\r", "\r\n") => 1# f_p_a_e("qwertydkjf", "\r\n") => 0# f_p_a_e("qwerty\r\n", "\r\n") => <undefined>
# this could maybe be made faster with a computed regex?# [answer: no; circa Python-2.0, Jan 2001]# new python: 28961/s# old python: 18307/s# re: 12820/s# regex: 14035/s
def find_prefix_at_end(haystack, needle): l = len(needle) - 1 while l and not haystack.endswith(needle[:l]): l -= 1 return l12345678910111213141516171819202122232425262728293031323334353637383940414243"""The asyncio package, tracking PEP 3156."""
# flake8: noqa
import sys
# This relies on each of the submodules having an __all__ variable.from .base_events import *from .coroutines import *from .events import *from .exceptions import *from .futures import *from .locks import *from .protocols import *from .runners import *from .queues import *from .streams import *from .subprocess import *from .tasks import *from .threads import *from .transports import *
__all__ = (base_events.__all__ + coroutines.__all__ + events.__all__ + exceptions.__all__ + futures.__all__ + locks.__all__ + protocols.__all__ + runners.__all__ + queues.__all__ + streams.__all__ + subprocess.__all__ + tasks.__all__ + threads.__all__ + transports.__all__)
if sys.platform == 'win32': # pragma: no cover from .windows_events import * __all__ += windows_events.__all__else: from .unix_events import * # pragma: no cover __all__ += unix_events.__all__123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125import astimport asyncioimport codeimport concurrent.futuresimport inspectimport sysimport threadingimport typesimport warnings
from . import futures
class AsyncIOInteractiveConsole(code.InteractiveConsole):
def __init__(self, locals, loop): super().__init__(locals) self.compile.compiler.flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
self.loop = loop
def runcode(self, code): future = concurrent.futures.Future()
def callback(): global repl_future global repl_future_interrupted
repl_future = None repl_future_interrupted = False
func = types.FunctionType(code, self.locals) try: coro = func() except SystemExit: raise except KeyboardInterrupt as ex: repl_future_interrupted = True future.set_exception(ex) return except BaseException as ex: future.set_exception(ex) return
if not inspect.iscoroutine(coro): future.set_result(coro) return
try: repl_future = self.loop.create_task(coro) futures._chain_future(repl_future, future) except BaseException as exc: future.set_exception(exc)
loop.call_soon_threadsafe(callback)
try: return future.result() except SystemExit: raise except BaseException: if repl_future_interrupted: self.write("\nKeyboardInterrupt\n") else: self.showtraceback()
class REPLThread(threading.Thread):
def run(self): try: banner = ( f'asyncio REPL {sys.version} on {sys.platform}\n' f'Use "await" directly instead of "asyncio.run()".\n' f'Type "help", "copyright", "credits" or "license" ' f'for more information.\n' f'{getattr(sys, "ps1", ">>> ")}import asyncio' )
console.interact( banner=banner, exitmsg='exiting asyncio REPL...') finally: warnings.filterwarnings( 'ignore', message=r'^coroutine .* was never awaited$', category=RuntimeWarning)
loop.call_soon_threadsafe(loop.stop)
if __name__ == '__main__': loop = asyncio.new_event_loop() asyncio.set_event_loop(loop)
repl_locals = {'asyncio': asyncio} for key in {'__name__', '__package__', '__loader__', '__spec__', '__builtins__', '__file__'}: repl_locals[key] = locals()[key]
console = AsyncIOInteractiveConsole(repl_locals, loop)
repl_future = None repl_future_interrupted = False
try: import readline # NoQA except ImportError: pass
repl_thread = REPLThread() repl_thread.daemon = True repl_thread.start()
while True: try: loop.run_forever() except KeyboardInterrupt: if repl_future and not repl_future.done(): repl_future.cancel() repl_future_interrupted = True continue else: break.gitattributes+36
Pytorch/.nonadminAdded
Pytorch/DLLs/_asyncio.pydAdded
Pytorch/DLLs/_bz2.pydAdded
Pytorch/DLLs/_ctypes.pydAdded
Pytorch/DLLs/_ctypes_test.pydAdded
Pytorch/DLLs/_decimal.pydAdded
Pytorch/DLLs/_elementtree.pydAdded
Pytorch/DLLs/_hashlib.pydAdded
Pytorch/DLLs/_lzma.pydAdded
Pytorch/DLLs/_msi.pydAdded
Pytorch/DLLs/_multiprocessing.pydAdded
Pytorch/DLLs/_overlapped.pydAdded
Pytorch/DLLs/_queue.pydAdded
Pytorch/DLLs/_socket.pydAdded
Pytorch/DLLs/_sqlite3.pydAdded
Pytorch/DLLs/_ssl.pydAdded
Pytorch/DLLs/_testbuffer.pydAdded
Pytorch/DLLs/_testcapi.pydAdded
Pytorch/DLLs/_testconsole.pydAdded
Pytorch/DLLs/_testimportmultiple.pydAdded
Pytorch/DLLs/_testinternalcapi.pydAdded
Pytorch/DLLs/_testmultiphase.pydAdded
Pytorch/DLLs/_tkinter.pydAdded
Pytorch/DLLs/_uuid.pydAdded
Pytorch/DLLs/_zoneinfo.pydAdded
Pytorch/DLLs/py.icoAdded
Pytorch/DLLs/pyc.icoAdded
Pytorch/DLLs/pyexpat.pydAdded
Pytorch/DLLs/select.pydAdded
Pytorch/DLLs/unicodedata.pydAdded+3
Pytorch/DLLs/winsound.pydAdded
Pytorch/DLLs/xxlimited.pydAdded
Pytorch/DLLs/xxlimited_35.pydAdded
Pytorch/LICENSE_PYTHON.txtAdded+279
Pytorch/Lib/abc.pyAdded+188
Pytorch/Lib/aifc.pyAdded+947
Pytorch/Lib/antigravity.pyAdded+17
Pytorch/Lib/argparse.pyAdded
Pytorch/Lib/ast.pyAdded+1709
Pytorch/Lib/asynchat.pyAdded+315
Pytorch/Lib/asyncio/__init__.pyAdded+43
Pytorch/Lib/asyncio/__main__.pyAdded+125
Pytorch/Lib/asyncio/__pycache__/__init__.cpython-310.pycAdded
Pytorch/Lib/asyncio/__pycache__/__main__.cpython-310.pycAdded
Pytorch/Lib/asyncio/__pycache__/base_events.cpython-310.pycAdded
Pytorch/Lib/asyncio/__pycache__/base_futures.cpython-310.pycAdded
Pytorch/Lib/asyncio/__pycache__/base_subprocess.cpython-310.pycAdded
Pytorch/Lib/asyncio/__pycache__/base_tasks.cpython-310.pycAdded
Pytorch/Lib/asyncio/__pycache__/constants.cpython-310.pycAdded