from contextlib import contextmanager, nullcontext
from enum import IntEnum, auto, _simple_enum
-__all__ = ('unparse',)
-
# 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)
_MULTI_QUOTES = ('"""', "'''")
_ALL_QUOTES = (*_SINGLE_QUOTES, *_MULTI_QUOTES)
-class _Unparser(NodeVisitor):
+class Unparser(NodeVisitor):
"""Methods in this class recursively traverse an AST and
output source code for the abstract syntax; original formatting
is disregarded."""
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)
-unparse.__module__ = 'ast' # backwards compatibility
:copyright: Copyright 2008 by Armin Ronacher.
:license: Python License.
"""
-import sys
from _ast import *
"""Deprecated AST node class. Unused in Python 3."""
+def unparse(ast_obj):
+ global _Unparser
+ try:
+ unparser = _Unparser()
+ except NameError:
+ from _ast_unparse import Unparser as _Unparser
+ unparser = _Unparser()
+ return unparser.visit(ast_obj)
+
+
def main():
import argparse
+ import sys
parser = argparse.ArgumentParser()
parser.add_argument('infile', nargs='?', default='-',
if __name__ == '__main__':
main()
-
-def __dir__():
- dir_ = {n for n in globals() if not n.startswith('_') and n != 'sys'}
- return sorted(dir_ | {'unparse'})
-
-def __getattr__(name):
- if name == 'unparse':
- global unparse
- from _ast_unparse import unparse
- return unparse
-
- raise AttributeError(f'module {__name__!r} has no attribute {name!r}')