index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
39,140
astunparse.printer
write
null
def write(self, text): self.f.write(six.text_type(text))
(self, text)
39,141
astunparse.unparser
Unparser
Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded.
class Unparser: """Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded. """ def __init__(self, tree, file = sys.stdout): """Unparser(tree, file=sys.stdout) -> None. Print the source for tree to file.""" self.f = file self.future_imports = [] self._indent = 0 self.dispatch(tree) print("", file=self.f) self.f.flush() def fill(self, text = ""): "Indent a piece of text, according to the current indentation level" self.f.write("\n"+" "*self._indent + text) def write(self, text): "Append a piece of text to the current line." self.f.write(six.text_type(text)) def enter(self): "Print ':', and increase the indentation." self.write(":") self._indent += 1 def leave(self): "Decrease the indentation level." self._indent -= 1 def dispatch(self, tree): "Dispatcher function, dispatching tree type T to method _T." if isinstance(tree, list): for t in tree: self.dispatch(t) return meth = getattr(self, "_"+tree.__class__.__name__) meth(tree) ############### Unparsing methods ###################### # There should be one method per concrete grammar type # # Constructors should be grouped by sum type. Ideally, # # this would follow the order in the grammar, but # # currently doesn't. # ######################################################## def _Module(self, tree): for stmt in tree.body: self.dispatch(stmt) def _Interactive(self, tree): for stmt in tree.body: self.dispatch(stmt) def _Expression(self, tree): self.dispatch(tree.body) # stmt def _Expr(self, tree): self.fill() self.dispatch(tree.value) def _NamedExpr(self, tree): self.write("(") self.dispatch(tree.target) self.write(" := ") self.dispatch(tree.value) self.write(")") def _Import(self, t): self.fill("import ") interleave(lambda: self.write(", "), self.dispatch, t.names) def _ImportFrom(self, t): # A from __future__ import may affect unparsing, so record it. if t.module and t.module == '__future__': self.future_imports.extend(n.name for n in t.names) self.fill("from ") self.write("." * t.level) if t.module: self.write(t.module) self.write(" import ") interleave(lambda: self.write(", "), self.dispatch, t.names) def _Assign(self, t): self.fill() for target in t.targets: self.dispatch(target) self.write(" = ") self.dispatch(t.value) def _AugAssign(self, t): self.fill() self.dispatch(t.target) self.write(" "+self.binop[t.op.__class__.__name__]+"= ") self.dispatch(t.value) def _AnnAssign(self, t): self.fill() if not t.simple and isinstance(t.target, ast.Name): self.write('(') self.dispatch(t.target) if not t.simple and isinstance(t.target, ast.Name): self.write(')') self.write(": ") self.dispatch(t.annotation) if t.value: self.write(" = ") self.dispatch(t.value) def _Return(self, t): self.fill("return") if t.value: self.write(" ") self.dispatch(t.value) def _Pass(self, t): self.fill("pass") def _Break(self, t): self.fill("break") def _Continue(self, t): self.fill("continue") def _Delete(self, t): self.fill("del ") interleave(lambda: self.write(", "), self.dispatch, t.targets) def _Assert(self, t): self.fill("assert ") self.dispatch(t.test) if t.msg: self.write(", ") self.dispatch(t.msg) def _Exec(self, t): self.fill("exec ") self.dispatch(t.body) if t.globals: self.write(" in ") self.dispatch(t.globals) if t.locals: self.write(", ") self.dispatch(t.locals) def _Print(self, t): self.fill("print ") do_comma = False if t.dest: self.write(">>") self.dispatch(t.dest) do_comma = True for e in t.values: if do_comma:self.write(", ") else:do_comma=True self.dispatch(e) if not t.nl: self.write(",") def _Global(self, t): self.fill("global ") interleave(lambda: self.write(", "), self.write, t.names) def _Nonlocal(self, t): self.fill("nonlocal ") interleave(lambda: self.write(", "), self.write, t.names) def _Await(self, t): self.write("(") self.write("await") if t.value: self.write(" ") self.dispatch(t.value) self.write(")") def _Yield(self, t): self.write("(") self.write("yield") if t.value: self.write(" ") self.dispatch(t.value) self.write(")") def _YieldFrom(self, t): self.write("(") self.write("yield from") if t.value: self.write(" ") self.dispatch(t.value) self.write(")") def _Raise(self, t): self.fill("raise") if six.PY3: if not t.exc: assert not t.cause return self.write(" ") self.dispatch(t.exc) if t.cause: self.write(" from ") self.dispatch(t.cause) else: self.write(" ") if t.type: self.dispatch(t.type) if t.inst: self.write(", ") self.dispatch(t.inst) if t.tback: self.write(", ") self.dispatch(t.tback) def _Try(self, t): self.fill("try") self.enter() self.dispatch(t.body) self.leave() for ex in t.handlers: self.dispatch(ex) if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() if t.finalbody: self.fill("finally") self.enter() self.dispatch(t.finalbody) self.leave() def _TryExcept(self, t): self.fill("try") self.enter() self.dispatch(t.body) self.leave() for ex in t.handlers: self.dispatch(ex) if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() def _TryFinally(self, t): if len(t.body) == 1 and isinstance(t.body[0], ast.TryExcept): # try-except-finally self.dispatch(t.body) else: self.fill("try") self.enter() self.dispatch(t.body) self.leave() self.fill("finally") self.enter() self.dispatch(t.finalbody) self.leave() def _ExceptHandler(self, t): self.fill("except") if t.type: self.write(" ") self.dispatch(t.type) if t.name: self.write(" as ") if six.PY3: self.write(t.name) else: self.dispatch(t.name) self.enter() self.dispatch(t.body) self.leave() def _ClassDef(self, t): self.write("\n") for deco in t.decorator_list: self.fill("@") self.dispatch(deco) self.fill("class "+t.name) if six.PY3: self.write("(") comma = False for e in t.bases: if comma: self.write(", ") else: comma = True self.dispatch(e) for e in t.keywords: if comma: self.write(", ") else: comma = True self.dispatch(e) if sys.version_info[:2] < (3, 5): if t.starargs: if comma: self.write(", ") else: comma = True self.write("*") self.dispatch(t.starargs) if t.kwargs: if comma: self.write(", ") else: comma = True self.write("**") self.dispatch(t.kwargs) self.write(")") elif t.bases: self.write("(") for a in t.bases: self.dispatch(a) self.write(", ") self.write(")") self.enter() self.dispatch(t.body) self.leave() def _FunctionDef(self, t): self.__FunctionDef_helper(t, "def") def _AsyncFunctionDef(self, t): self.__FunctionDef_helper(t, "async def") def __FunctionDef_helper(self, t, fill_suffix): self.write("\n") for deco in t.decorator_list: self.fill("@") self.dispatch(deco) def_str = fill_suffix+" "+t.name + "(" self.fill(def_str) self.dispatch(t.args) self.write(")") if getattr(t, "returns", False): self.write(" -> ") self.dispatch(t.returns) self.enter() self.dispatch(t.body) self.leave() def _For(self, t): self.__For_helper("for ", t) def _AsyncFor(self, t): self.__For_helper("async for ", t) def __For_helper(self, fill, t): self.fill(fill) self.dispatch(t.target) self.write(" in ") self.dispatch(t.iter) self.enter() self.dispatch(t.body) self.leave() if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() def _If(self, t): self.fill("if ") self.dispatch(t.test) self.enter() self.dispatch(t.body) self.leave() # collapse nested ifs into equivalent elifs. while (t.orelse and len(t.orelse) == 1 and isinstance(t.orelse[0], ast.If)): t = t.orelse[0] self.fill("elif ") self.dispatch(t.test) self.enter() self.dispatch(t.body) self.leave() # final else if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() def _While(self, t): self.fill("while ") self.dispatch(t.test) self.enter() self.dispatch(t.body) self.leave() if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() def _generic_With(self, t, async_=False): self.fill("async with " if async_ else "with ") if hasattr(t, 'items'): interleave(lambda: self.write(", "), self.dispatch, t.items) else: self.dispatch(t.context_expr) if t.optional_vars: self.write(" as ") self.dispatch(t.optional_vars) self.enter() self.dispatch(t.body) self.leave() def _With(self, t): self._generic_With(t) def _AsyncWith(self, t): self._generic_With(t, async_=True) # expr def _Bytes(self, t): self.write(repr(t.s)) def _Str(self, tree): if six.PY3: self.write(repr(tree.s)) else: # if from __future__ import unicode_literals is in effect, # then we want to output string literals using a 'b' prefix # and unicode literals with no prefix. if "unicode_literals" not in self.future_imports: self.write(repr(tree.s)) elif isinstance(tree.s, str): self.write("b" + repr(tree.s)) elif isinstance(tree.s, unicode): self.write(repr(tree.s).lstrip("u")) else: assert False, "shouldn't get here" def _JoinedStr(self, t): # JoinedStr(expr* values) self.write("f") string = StringIO() self._fstring_JoinedStr(t, string.write) # Deviation from `unparse.py`: Try to find an unused quote. # This change is made to handle _very_ complex f-strings. v = string.getvalue() if '\n' in v or '\r' in v: quote_types = ["'''", '"""'] else: quote_types = ["'", '"', '"""', "'''"] for quote_type in quote_types: if quote_type not in v: v = "{quote_type}{v}{quote_type}".format(quote_type=quote_type, v=v) break else: v = repr(v) self.write(v) def _FormattedValue(self, t): # FormattedValue(expr value, int? conversion, expr? format_spec) self.write("f") string = StringIO() self._fstring_JoinedStr(t, string.write) self.write(repr(string.getvalue())) def _fstring_JoinedStr(self, t, write): for value in t.values: meth = getattr(self, "_fstring_" + type(value).__name__) meth(value, write) def _fstring_Str(self, t, write): value = t.s.replace("{", "{{").replace("}", "}}") write(value) def _fstring_Constant(self, t, write): assert isinstance(t.value, str) value = t.value.replace("{", "{{").replace("}", "}}") write(value) def _fstring_FormattedValue(self, t, write): write("{") expr = StringIO() Unparser(t.value, expr) expr = expr.getvalue().rstrip("\n") if expr.startswith("{"): write(" ") # Separate pair of opening brackets as "{ {" write(expr) if t.conversion != -1: conversion = chr(t.conversion) assert conversion in "sra" write("!{conversion}".format(conversion=conversion)) if t.format_spec: write(":") meth = getattr(self, "_fstring_" + type(t.format_spec).__name__) meth(t.format_spec, write) write("}") def _Name(self, t): self.write(t.id) def _NameConstant(self, t): self.write(repr(t.value)) def _Repr(self, t): self.write("`") self.dispatch(t.value) self.write("`") def _write_constant(self, value): if isinstance(value, (float, complex)): # Substitute overflowing decimal literal for AST infinities. self.write(repr(value).replace("inf", INFSTR)) else: self.write(repr(value)) def _Constant(self, t): value = t.value if isinstance(value, tuple): self.write("(") if len(value) == 1: self._write_constant(value[0]) self.write(",") else: interleave(lambda: self.write(", "), self._write_constant, value) self.write(")") elif value is Ellipsis: # instead of `...` for Py2 compatibility self.write("...") else: if t.kind == "u": self.write("u") self._write_constant(t.value) def _Num(self, t): repr_n = repr(t.n) if six.PY3: self.write(repr_n.replace("inf", INFSTR)) else: # Parenthesize negative numbers, to avoid turning (-1)**2 into -1**2. if repr_n.startswith("-"): self.write("(") if "inf" in repr_n and repr_n.endswith("*j"): repr_n = repr_n.replace("*j", "j") # Substitute overflowing decimal literal for AST infinities. self.write(repr_n.replace("inf", INFSTR)) if repr_n.startswith("-"): self.write(")") def _List(self, t): self.write("[") interleave(lambda: self.write(", "), self.dispatch, t.elts) self.write("]") def _ListComp(self, t): self.write("[") self.dispatch(t.elt) for gen in t.generators: self.dispatch(gen) self.write("]") def _GeneratorExp(self, t): self.write("(") self.dispatch(t.elt) for gen in t.generators: self.dispatch(gen) self.write(")") def _SetComp(self, t): self.write("{") self.dispatch(t.elt) for gen in t.generators: self.dispatch(gen) self.write("}") def _DictComp(self, t): self.write("{") self.dispatch(t.key) self.write(": ") self.dispatch(t.value) for gen in t.generators: self.dispatch(gen) self.write("}") def _comprehension(self, t): if getattr(t, 'is_async', False): self.write(" async for ") else: self.write(" for ") self.dispatch(t.target) self.write(" in ") self.dispatch(t.iter) for if_clause in t.ifs: self.write(" if ") self.dispatch(if_clause) def _IfExp(self, t): self.write("(") self.dispatch(t.body) self.write(" if ") self.dispatch(t.test) self.write(" else ") self.dispatch(t.orelse) self.write(")") def _Set(self, t): assert(t.elts) # should be at least one element self.write("{") interleave(lambda: self.write(", "), self.dispatch, t.elts) self.write("}") def _Dict(self, t): self.write("{") def write_key_value_pair(k, v): self.dispatch(k) self.write(": ") self.dispatch(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.dispatch(v) else: write_key_value_pair(k, v) interleave(lambda: self.write(", "), write_item, zip(t.keys, t.values)) self.write("}") def _Tuple(self, t): self.write("(") if len(t.elts) == 1: elt = t.elts[0] self.dispatch(elt) self.write(",") else: interleave(lambda: self.write(", "), self.dispatch, t.elts) self.write(")") unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"} def _UnaryOp(self, t): self.write("(") self.write(self.unop[t.op.__class__.__name__]) self.write(" ") if six.PY2 and isinstance(t.op, ast.USub) and isinstance(t.operand, ast.Num): # If we're applying unary minus to a number, parenthesize the number. # This is necessary: -2147483648 is different from -(2147483648) on # a 32-bit machine (the first is an int, the second a long), and # -7j is different from -(7j). (The first has real part 0.0, the second # has real part -0.0.) self.write("(") self.dispatch(t.operand) self.write(")") else: self.dispatch(t.operand) self.write(")") binop = { "Add":"+", "Sub":"-", "Mult":"*", "MatMult":"@", "Div":"/", "Mod":"%", "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&", "FloorDiv":"//", "Pow": "**"} def _BinOp(self, t): self.write("(") self.dispatch(t.left) self.write(" " + self.binop[t.op.__class__.__name__] + " ") self.dispatch(t.right) self.write(")") cmpops = {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=", "Is":"is", "IsNot":"is not", "In":"in", "NotIn":"not in"} def _Compare(self, t): self.write("(") self.dispatch(t.left) for o, e in zip(t.ops, t.comparators): self.write(" " + self.cmpops[o.__class__.__name__] + " ") self.dispatch(e) self.write(")") boolops = {ast.And: 'and', ast.Or: 'or'} def _BoolOp(self, t): self.write("(") s = " %s " % self.boolops[t.op.__class__] interleave(lambda: self.write(s), self.dispatch, t.values) self.write(")") def _Attribute(self,t): self.dispatch(t.value) # Special case: 3.__abs__() is a syntax error, so if t.value # is an integer literal then we need to either parenthesize # it or add an extra space to get 3 .__abs__(). if isinstance(t.value, getattr(ast, 'Constant', getattr(ast, 'Num', None))) and isinstance(t.value.n, int): self.write(" ") self.write(".") self.write(t.attr) def _Call(self, t): self.dispatch(t.func) self.write("(") comma = False for e in t.args: if comma: self.write(", ") else: comma = True self.dispatch(e) for e in t.keywords: if comma: self.write(", ") else: comma = True self.dispatch(e) if sys.version_info[:2] < (3, 5): if t.starargs: if comma: self.write(", ") else: comma = True self.write("*") self.dispatch(t.starargs) if t.kwargs: if comma: self.write(", ") else: comma = True self.write("**") self.dispatch(t.kwargs) self.write(")") def _Subscript(self, t): self.dispatch(t.value) self.write("[") self.dispatch(t.slice) self.write("]") def _Starred(self, t): self.write("*") self.dispatch(t.value) # slice def _Ellipsis(self, t): self.write("...") def _Index(self, t): self.dispatch(t.value) def _Slice(self, t): if t.lower: self.dispatch(t.lower) self.write(":") if t.upper: self.dispatch(t.upper) if t.step: self.write(":") self.dispatch(t.step) def _ExtSlice(self, t): interleave(lambda: self.write(', '), self.dispatch, t.dims) # argument def _arg(self, t): self.write(t.arg) if t.annotation: self.write(": ") self.dispatch(t.annotation) # others def _arguments(self, t): first = True # normal arguments all_args = getattr(t, 'posonlyargs', []) + t.args defaults = [None] * (len(all_args) - len(t.defaults)) + t.defaults for index, elements in enumerate(zip(all_args, defaults), 1): a, d = elements if first:first = False else: self.write(", ") self.dispatch(a) if d: self.write("=") self.dispatch(d) if index == len(getattr(t, 'posonlyargs', ())): self.write(", /") # varargs, or bare '*' if no varargs but keyword-only arguments present if t.vararg or getattr(t, "kwonlyargs", False): if first:first = False else: self.write(", ") self.write("*") if t.vararg: if hasattr(t.vararg, 'arg'): self.write(t.vararg.arg) if t.vararg.annotation: self.write(": ") self.dispatch(t.vararg.annotation) else: self.write(t.vararg) if getattr(t, 'varargannotation', None): self.write(": ") self.dispatch(t.varargannotation) # keyword-only arguments if getattr(t, "kwonlyargs", False): for a, d in zip(t.kwonlyargs, t.kw_defaults): if first:first = False else: self.write(", ") self.dispatch(a), if d: self.write("=") self.dispatch(d) # kwargs if t.kwarg: if first:first = False else: self.write(", ") if hasattr(t.kwarg, 'arg'): self.write("**"+t.kwarg.arg) if t.kwarg.annotation: self.write(": ") self.dispatch(t.kwarg.annotation) else: self.write("**"+t.kwarg) if getattr(t, 'kwargannotation', None): self.write(": ") self.dispatch(t.kwargannotation) def _keyword(self, t): if t.arg is None: # starting from Python 3.5 this denotes a kwargs part of the invocation self.write("**") else: self.write(t.arg) self.write("=") self.dispatch(t.value) def _Lambda(self, t): self.write("(") self.write("lambda ") self.dispatch(t.args) self.write(": ") self.dispatch(t.body) self.write(")") def _alias(self, t): self.write(t.name) if t.asname: self.write(" as "+t.asname) def _withitem(self, t): self.dispatch(t.context_expr) if t.optional_vars: self.write(" as ") self.dispatch(t.optional_vars)
(tree, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)
39,142
astunparse.unparser
_AnnAssign
null
def _AnnAssign(self, t): self.fill() if not t.simple and isinstance(t.target, ast.Name): self.write('(') self.dispatch(t.target) if not t.simple and isinstance(t.target, ast.Name): self.write(')') self.write(": ") self.dispatch(t.annotation) if t.value: self.write(" = ") self.dispatch(t.value)
(self, t)
39,143
astunparse.unparser
_Assert
null
def _Assert(self, t): self.fill("assert ") self.dispatch(t.test) if t.msg: self.write(", ") self.dispatch(t.msg)
(self, t)
39,144
astunparse.unparser
_Assign
null
def _Assign(self, t): self.fill() for target in t.targets: self.dispatch(target) self.write(" = ") self.dispatch(t.value)
(self, t)
39,145
astunparse.unparser
_AsyncFor
null
def _AsyncFor(self, t): self.__For_helper("async for ", t)
(self, t)
39,146
astunparse.unparser
_AsyncFunctionDef
null
def _AsyncFunctionDef(self, t): self.__FunctionDef_helper(t, "async def")
(self, t)
39,147
astunparse.unparser
_AsyncWith
null
def _AsyncWith(self, t): self._generic_With(t, async_=True)
(self, t)
39,148
astunparse.unparser
_Attribute
null
def _Attribute(self,t): self.dispatch(t.value) # Special case: 3.__abs__() is a syntax error, so if t.value # is an integer literal then we need to either parenthesize # it or add an extra space to get 3 .__abs__(). if isinstance(t.value, getattr(ast, 'Constant', getattr(ast, 'Num', None))) and isinstance(t.value.n, int): self.write(" ") self.write(".") self.write(t.attr)
(self, t)
39,149
astunparse.unparser
_AugAssign
null
def _AugAssign(self, t): self.fill() self.dispatch(t.target) self.write(" "+self.binop[t.op.__class__.__name__]+"= ") self.dispatch(t.value)
(self, t)
39,150
astunparse.unparser
_Await
null
def _Await(self, t): self.write("(") self.write("await") if t.value: self.write(" ") self.dispatch(t.value) self.write(")")
(self, t)
39,151
astunparse.unparser
_BinOp
null
def _BinOp(self, t): self.write("(") self.dispatch(t.left) self.write(" " + self.binop[t.op.__class__.__name__] + " ") self.dispatch(t.right) self.write(")")
(self, t)
39,152
astunparse.unparser
_BoolOp
null
def _BoolOp(self, t): self.write("(") s = " %s " % self.boolops[t.op.__class__] interleave(lambda: self.write(s), self.dispatch, t.values) self.write(")")
(self, t)
39,153
astunparse.unparser
_Break
null
def _Break(self, t): self.fill("break")
(self, t)
39,154
astunparse.unparser
_Bytes
null
def _Bytes(self, t): self.write(repr(t.s))
(self, t)
39,155
astunparse.unparser
_Call
null
def _Call(self, t): self.dispatch(t.func) self.write("(") comma = False for e in t.args: if comma: self.write(", ") else: comma = True self.dispatch(e) for e in t.keywords: if comma: self.write(", ") else: comma = True self.dispatch(e) if sys.version_info[:2] < (3, 5): if t.starargs: if comma: self.write(", ") else: comma = True self.write("*") self.dispatch(t.starargs) if t.kwargs: if comma: self.write(", ") else: comma = True self.write("**") self.dispatch(t.kwargs) self.write(")")
(self, t)
39,156
astunparse.unparser
_ClassDef
null
def _ClassDef(self, t): self.write("\n") for deco in t.decorator_list: self.fill("@") self.dispatch(deco) self.fill("class "+t.name) if six.PY3: self.write("(") comma = False for e in t.bases: if comma: self.write(", ") else: comma = True self.dispatch(e) for e in t.keywords: if comma: self.write(", ") else: comma = True self.dispatch(e) if sys.version_info[:2] < (3, 5): if t.starargs: if comma: self.write(", ") else: comma = True self.write("*") self.dispatch(t.starargs) if t.kwargs: if comma: self.write(", ") else: comma = True self.write("**") self.dispatch(t.kwargs) self.write(")") elif t.bases: self.write("(") for a in t.bases: self.dispatch(a) self.write(", ") self.write(")") self.enter() self.dispatch(t.body) self.leave()
(self, t)
39,157
astunparse.unparser
_Compare
null
def _Compare(self, t): self.write("(") self.dispatch(t.left) for o, e in zip(t.ops, t.comparators): self.write(" " + self.cmpops[o.__class__.__name__] + " ") self.dispatch(e) self.write(")")
(self, t)
39,158
astunparse.unparser
_Constant
null
def _Constant(self, t): value = t.value if isinstance(value, tuple): self.write("(") if len(value) == 1: self._write_constant(value[0]) self.write(",") else: interleave(lambda: self.write(", "), self._write_constant, value) self.write(")") elif value is Ellipsis: # instead of `...` for Py2 compatibility self.write("...") else: if t.kind == "u": self.write("u") self._write_constant(t.value)
(self, t)
39,159
astunparse.unparser
_Continue
null
def _Continue(self, t): self.fill("continue")
(self, t)
39,160
astunparse.unparser
_Delete
null
def _Delete(self, t): self.fill("del ") interleave(lambda: self.write(", "), self.dispatch, t.targets)
(self, t)
39,161
astunparse.unparser
_Dict
null
def _Dict(self, t): self.write("{") def write_key_value_pair(k, v): self.dispatch(k) self.write(": ") self.dispatch(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.dispatch(v) else: write_key_value_pair(k, v) interleave(lambda: self.write(", "), write_item, zip(t.keys, t.values)) self.write("}")
(self, t)
39,162
astunparse.unparser
_DictComp
null
def _DictComp(self, t): self.write("{") self.dispatch(t.key) self.write(": ") self.dispatch(t.value) for gen in t.generators: self.dispatch(gen) self.write("}")
(self, t)
39,163
astunparse.unparser
_Ellipsis
null
def _Ellipsis(self, t): self.write("...")
(self, t)
39,164
astunparse.unparser
_ExceptHandler
null
def _ExceptHandler(self, t): self.fill("except") if t.type: self.write(" ") self.dispatch(t.type) if t.name: self.write(" as ") if six.PY3: self.write(t.name) else: self.dispatch(t.name) self.enter() self.dispatch(t.body) self.leave()
(self, t)
39,165
astunparse.unparser
_Exec
null
def _Exec(self, t): self.fill("exec ") self.dispatch(t.body) if t.globals: self.write(" in ") self.dispatch(t.globals) if t.locals: self.write(", ") self.dispatch(t.locals)
(self, t)
39,166
astunparse.unparser
_Expr
null
def _Expr(self, tree): self.fill() self.dispatch(tree.value)
(self, tree)
39,167
astunparse.unparser
_Expression
null
def _Expression(self, tree): self.dispatch(tree.body)
(self, tree)
39,168
astunparse.unparser
_ExtSlice
null
def _ExtSlice(self, t): interleave(lambda: self.write(', '), self.dispatch, t.dims)
(self, t)
39,169
astunparse.unparser
_For
null
def _For(self, t): self.__For_helper("for ", t)
(self, t)
39,170
astunparse.unparser
_FormattedValue
null
def _FormattedValue(self, t): # FormattedValue(expr value, int? conversion, expr? format_spec) self.write("f") string = StringIO() self._fstring_JoinedStr(t, string.write) self.write(repr(string.getvalue()))
(self, t)
39,171
astunparse.unparser
_FunctionDef
null
def _FunctionDef(self, t): self.__FunctionDef_helper(t, "def")
(self, t)
39,172
astunparse.unparser
_GeneratorExp
null
def _GeneratorExp(self, t): self.write("(") self.dispatch(t.elt) for gen in t.generators: self.dispatch(gen) self.write(")")
(self, t)
39,173
astunparse.unparser
_Global
null
def _Global(self, t): self.fill("global ") interleave(lambda: self.write(", "), self.write, t.names)
(self, t)
39,174
astunparse.unparser
_If
null
def _If(self, t): self.fill("if ") self.dispatch(t.test) self.enter() self.dispatch(t.body) self.leave() # collapse nested ifs into equivalent elifs. while (t.orelse and len(t.orelse) == 1 and isinstance(t.orelse[0], ast.If)): t = t.orelse[0] self.fill("elif ") self.dispatch(t.test) self.enter() self.dispatch(t.body) self.leave() # final else if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave()
(self, t)
39,175
astunparse.unparser
_IfExp
null
def _IfExp(self, t): self.write("(") self.dispatch(t.body) self.write(" if ") self.dispatch(t.test) self.write(" else ") self.dispatch(t.orelse) self.write(")")
(self, t)
39,176
astunparse.unparser
_Import
null
def _Import(self, t): self.fill("import ") interleave(lambda: self.write(", "), self.dispatch, t.names)
(self, t)
39,177
astunparse.unparser
_ImportFrom
null
def _ImportFrom(self, t): # A from __future__ import may affect unparsing, so record it. if t.module and t.module == '__future__': self.future_imports.extend(n.name for n in t.names) self.fill("from ") self.write("." * t.level) if t.module: self.write(t.module) self.write(" import ") interleave(lambda: self.write(", "), self.dispatch, t.names)
(self, t)
39,178
astunparse.unparser
_Index
null
def _Index(self, t): self.dispatch(t.value)
(self, t)
39,179
astunparse.unparser
_Interactive
null
def _Interactive(self, tree): for stmt in tree.body: self.dispatch(stmt)
(self, tree)
39,180
astunparse.unparser
_JoinedStr
null
def _JoinedStr(self, t): # JoinedStr(expr* values) self.write("f") string = StringIO() self._fstring_JoinedStr(t, string.write) # Deviation from `unparse.py`: Try to find an unused quote. # This change is made to handle _very_ complex f-strings. v = string.getvalue() if '\n' in v or '\r' in v: quote_types = ["'''", '"""'] else: quote_types = ["'", '"', '"""', "'''"] for quote_type in quote_types: if quote_type not in v: v = "{quote_type}{v}{quote_type}".format(quote_type=quote_type, v=v) break else: v = repr(v) self.write(v)
(self, t)
39,181
astunparse.unparser
_Lambda
null
def _Lambda(self, t): self.write("(") self.write("lambda ") self.dispatch(t.args) self.write(": ") self.dispatch(t.body) self.write(")")
(self, t)
39,182
astunparse.unparser
_List
null
def _List(self, t): self.write("[") interleave(lambda: self.write(", "), self.dispatch, t.elts) self.write("]")
(self, t)
39,183
astunparse.unparser
_ListComp
null
def _ListComp(self, t): self.write("[") self.dispatch(t.elt) for gen in t.generators: self.dispatch(gen) self.write("]")
(self, t)
39,184
astunparse.unparser
_Module
null
def _Module(self, tree): for stmt in tree.body: self.dispatch(stmt)
(self, tree)
39,185
astunparse.unparser
_Name
null
def _Name(self, t): self.write(t.id)
(self, t)
39,186
astunparse.unparser
_NameConstant
null
def _NameConstant(self, t): self.write(repr(t.value))
(self, t)
39,187
astunparse.unparser
_NamedExpr
null
def _NamedExpr(self, tree): self.write("(") self.dispatch(tree.target) self.write(" := ") self.dispatch(tree.value) self.write(")")
(self, tree)
39,188
astunparse.unparser
_Nonlocal
null
def _Nonlocal(self, t): self.fill("nonlocal ") interleave(lambda: self.write(", "), self.write, t.names)
(self, t)
39,189
astunparse.unparser
_Num
null
def _Num(self, t): repr_n = repr(t.n) if six.PY3: self.write(repr_n.replace("inf", INFSTR)) else: # Parenthesize negative numbers, to avoid turning (-1)**2 into -1**2. if repr_n.startswith("-"): self.write("(") if "inf" in repr_n and repr_n.endswith("*j"): repr_n = repr_n.replace("*j", "j") # Substitute overflowing decimal literal for AST infinities. self.write(repr_n.replace("inf", INFSTR)) if repr_n.startswith("-"): self.write(")")
(self, t)
39,190
astunparse.unparser
_Pass
null
def _Pass(self, t): self.fill("pass")
(self, t)
39,191
astunparse.unparser
_Print
null
def _Print(self, t): self.fill("print ") do_comma = False if t.dest: self.write(">>") self.dispatch(t.dest) do_comma = True for e in t.values: if do_comma:self.write(", ") else:do_comma=True self.dispatch(e) if not t.nl: self.write(",")
(self, t)
39,192
astunparse.unparser
_Raise
null
def _Raise(self, t): self.fill("raise") if six.PY3: if not t.exc: assert not t.cause return self.write(" ") self.dispatch(t.exc) if t.cause: self.write(" from ") self.dispatch(t.cause) else: self.write(" ") if t.type: self.dispatch(t.type) if t.inst: self.write(", ") self.dispatch(t.inst) if t.tback: self.write(", ") self.dispatch(t.tback)
(self, t)
39,193
astunparse.unparser
_Repr
null
def _Repr(self, t): self.write("`") self.dispatch(t.value) self.write("`")
(self, t)
39,194
astunparse.unparser
_Return
null
def _Return(self, t): self.fill("return") if t.value: self.write(" ") self.dispatch(t.value)
(self, t)
39,195
astunparse.unparser
_Set
null
def _Set(self, t): assert(t.elts) # should be at least one element self.write("{") interleave(lambda: self.write(", "), self.dispatch, t.elts) self.write("}")
(self, t)
39,196
astunparse.unparser
_SetComp
null
def _SetComp(self, t): self.write("{") self.dispatch(t.elt) for gen in t.generators: self.dispatch(gen) self.write("}")
(self, t)
39,197
astunparse.unparser
_Slice
null
def _Slice(self, t): if t.lower: self.dispatch(t.lower) self.write(":") if t.upper: self.dispatch(t.upper) if t.step: self.write(":") self.dispatch(t.step)
(self, t)
39,198
astunparse.unparser
_Starred
null
def _Starred(self, t): self.write("*") self.dispatch(t.value)
(self, t)
39,199
astunparse.unparser
_Str
null
def _Str(self, tree): if six.PY3: self.write(repr(tree.s)) else: # if from __future__ import unicode_literals is in effect, # then we want to output string literals using a 'b' prefix # and unicode literals with no prefix. if "unicode_literals" not in self.future_imports: self.write(repr(tree.s)) elif isinstance(tree.s, str): self.write("b" + repr(tree.s)) elif isinstance(tree.s, unicode): self.write(repr(tree.s).lstrip("u")) else: assert False, "shouldn't get here"
(self, tree)
39,200
astunparse.unparser
_Subscript
null
def _Subscript(self, t): self.dispatch(t.value) self.write("[") self.dispatch(t.slice) self.write("]")
(self, t)
39,201
astunparse.unparser
_Try
null
def _Try(self, t): self.fill("try") self.enter() self.dispatch(t.body) self.leave() for ex in t.handlers: self.dispatch(ex) if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() if t.finalbody: self.fill("finally") self.enter() self.dispatch(t.finalbody) self.leave()
(self, t)
39,202
astunparse.unparser
_TryExcept
null
def _TryExcept(self, t): self.fill("try") self.enter() self.dispatch(t.body) self.leave() for ex in t.handlers: self.dispatch(ex) if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave()
(self, t)
39,203
astunparse.unparser
_TryFinally
null
def _TryFinally(self, t): if len(t.body) == 1 and isinstance(t.body[0], ast.TryExcept): # try-except-finally self.dispatch(t.body) else: self.fill("try") self.enter() self.dispatch(t.body) self.leave() self.fill("finally") self.enter() self.dispatch(t.finalbody) self.leave()
(self, t)
39,204
astunparse.unparser
_Tuple
null
def _Tuple(self, t): self.write("(") if len(t.elts) == 1: elt = t.elts[0] self.dispatch(elt) self.write(",") else: interleave(lambda: self.write(", "), self.dispatch, t.elts) self.write(")")
(self, t)
39,205
astunparse.unparser
_UnaryOp
null
def _UnaryOp(self, t): self.write("(") self.write(self.unop[t.op.__class__.__name__]) self.write(" ") if six.PY2 and isinstance(t.op, ast.USub) and isinstance(t.operand, ast.Num): # If we're applying unary minus to a number, parenthesize the number. # This is necessary: -2147483648 is different from -(2147483648) on # a 32-bit machine (the first is an int, the second a long), and # -7j is different from -(7j). (The first has real part 0.0, the second # has real part -0.0.) self.write("(") self.dispatch(t.operand) self.write(")") else: self.dispatch(t.operand) self.write(")")
(self, t)
39,206
astunparse.unparser
__For_helper
null
def __For_helper(self, fill, t): self.fill(fill) self.dispatch(t.target) self.write(" in ") self.dispatch(t.iter) self.enter() self.dispatch(t.body) self.leave() if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave()
(self, fill, t)
39,207
astunparse.unparser
__FunctionDef_helper
null
def __FunctionDef_helper(self, t, fill_suffix): self.write("\n") for deco in t.decorator_list: self.fill("@") self.dispatch(deco) def_str = fill_suffix+" "+t.name + "(" self.fill(def_str) self.dispatch(t.args) self.write(")") if getattr(t, "returns", False): self.write(" -> ") self.dispatch(t.returns) self.enter() self.dispatch(t.body) self.leave()
(self, t, fill_suffix)
39,208
astunparse.unparser
_While
null
def _While(self, t): self.fill("while ") self.dispatch(t.test) self.enter() self.dispatch(t.body) self.leave() if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave()
(self, t)
39,209
astunparse.unparser
_With
null
def _With(self, t): self._generic_With(t)
(self, t)
39,210
astunparse.unparser
_Yield
null
def _Yield(self, t): self.write("(") self.write("yield") if t.value: self.write(" ") self.dispatch(t.value) self.write(")")
(self, t)
39,211
astunparse.unparser
_YieldFrom
null
def _YieldFrom(self, t): self.write("(") self.write("yield from") if t.value: self.write(" ") self.dispatch(t.value) self.write(")")
(self, t)
39,212
astunparse.unparser
__init__
Unparser(tree, file=sys.stdout) -> None. Print the source for tree to file.
def __init__(self, tree, file = sys.stdout): """Unparser(tree, file=sys.stdout) -> None. Print the source for tree to file.""" self.f = file self.future_imports = [] self._indent = 0 self.dispatch(tree) print("", file=self.f) self.f.flush()
(self, tree, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)
39,213
astunparse.unparser
_alias
null
def _alias(self, t): self.write(t.name) if t.asname: self.write(" as "+t.asname)
(self, t)
39,214
astunparse.unparser
_arg
null
def _arg(self, t): self.write(t.arg) if t.annotation: self.write(": ") self.dispatch(t.annotation)
(self, t)
39,215
astunparse.unparser
_arguments
null
def _arguments(self, t): first = True # normal arguments all_args = getattr(t, 'posonlyargs', []) + t.args defaults = [None] * (len(all_args) - len(t.defaults)) + t.defaults for index, elements in enumerate(zip(all_args, defaults), 1): a, d = elements if first:first = False else: self.write(", ") self.dispatch(a) if d: self.write("=") self.dispatch(d) if index == len(getattr(t, 'posonlyargs', ())): self.write(", /") # varargs, or bare '*' if no varargs but keyword-only arguments present if t.vararg or getattr(t, "kwonlyargs", False): if first:first = False else: self.write(", ") self.write("*") if t.vararg: if hasattr(t.vararg, 'arg'): self.write(t.vararg.arg) if t.vararg.annotation: self.write(": ") self.dispatch(t.vararg.annotation) else: self.write(t.vararg) if getattr(t, 'varargannotation', None): self.write(": ") self.dispatch(t.varargannotation) # keyword-only arguments if getattr(t, "kwonlyargs", False): for a, d in zip(t.kwonlyargs, t.kw_defaults): if first:first = False else: self.write(", ") self.dispatch(a), if d: self.write("=") self.dispatch(d) # kwargs if t.kwarg: if first:first = False else: self.write(", ") if hasattr(t.kwarg, 'arg'): self.write("**"+t.kwarg.arg) if t.kwarg.annotation: self.write(": ") self.dispatch(t.kwarg.annotation) else: self.write("**"+t.kwarg) if getattr(t, 'kwargannotation', None): self.write(": ") self.dispatch(t.kwargannotation)
(self, t)
39,216
astunparse.unparser
_comprehension
null
def _comprehension(self, t): if getattr(t, 'is_async', False): self.write(" async for ") else: self.write(" for ") self.dispatch(t.target) self.write(" in ") self.dispatch(t.iter) for if_clause in t.ifs: self.write(" if ") self.dispatch(if_clause)
(self, t)
39,217
astunparse.unparser
_fstring_Constant
null
def _fstring_Constant(self, t, write): assert isinstance(t.value, str) value = t.value.replace("{", "{{").replace("}", "}}") write(value)
(self, t, write)
39,218
astunparse.unparser
_fstring_FormattedValue
null
def _fstring_FormattedValue(self, t, write): write("{") expr = StringIO() Unparser(t.value, expr) expr = expr.getvalue().rstrip("\n") if expr.startswith("{"): write(" ") # Separate pair of opening brackets as "{ {" write(expr) if t.conversion != -1: conversion = chr(t.conversion) assert conversion in "sra" write("!{conversion}".format(conversion=conversion)) if t.format_spec: write(":") meth = getattr(self, "_fstring_" + type(t.format_spec).__name__) meth(t.format_spec, write) write("}")
(self, t, write)
39,219
astunparse.unparser
_fstring_JoinedStr
null
def _fstring_JoinedStr(self, t, write): for value in t.values: meth = getattr(self, "_fstring_" + type(value).__name__) meth(value, write)
(self, t, write)
39,220
astunparse.unparser
_fstring_Str
null
def _fstring_Str(self, t, write): value = t.s.replace("{", "{{").replace("}", "}}") write(value)
(self, t, write)
39,221
astunparse.unparser
_generic_With
null
def _generic_With(self, t, async_=False): self.fill("async with " if async_ else "with ") if hasattr(t, 'items'): interleave(lambda: self.write(", "), self.dispatch, t.items) else: self.dispatch(t.context_expr) if t.optional_vars: self.write(" as ") self.dispatch(t.optional_vars) self.enter() self.dispatch(t.body) self.leave()
(self, t, async_=False)
39,222
astunparse.unparser
_keyword
null
def _keyword(self, t): if t.arg is None: # starting from Python 3.5 this denotes a kwargs part of the invocation self.write("**") else: self.write(t.arg) self.write("=") self.dispatch(t.value)
(self, t)
39,223
astunparse.unparser
_withitem
null
def _withitem(self, t): self.dispatch(t.context_expr) if t.optional_vars: self.write(" as ") self.dispatch(t.optional_vars)
(self, t)
39,224
astunparse.unparser
_write_constant
null
def _write_constant(self, value): if isinstance(value, (float, complex)): # Substitute overflowing decimal literal for AST infinities. self.write(repr(value).replace("inf", INFSTR)) else: self.write(repr(value))
(self, value)
39,225
astunparse.unparser
dispatch
Dispatcher function, dispatching tree type T to method _T.
def dispatch(self, tree): "Dispatcher function, dispatching tree type T to method _T." if isinstance(tree, list): for t in tree: self.dispatch(t) return meth = getattr(self, "_"+tree.__class__.__name__) meth(tree)
(self, tree)
39,226
astunparse.unparser
enter
Print ':', and increase the indentation.
def enter(self): "Print ':', and increase the indentation." self.write(":") self._indent += 1
(self)
39,227
astunparse.unparser
fill
Indent a piece of text, according to the current indentation level
def fill(self, text = ""): "Indent a piece of text, according to the current indentation level" self.f.write("\n"+" "*self._indent + text)
(self, text='')
39,228
astunparse.unparser
leave
Decrease the indentation level.
def leave(self): "Decrease the indentation level." self._indent -= 1
(self)
39,229
astunparse.unparser
write
Append a piece of text to the current line.
def write(self, text): "Append a piece of text to the current line." self.f.write(six.text_type(text))
(self, text)
39,231
astunparse
dump
null
def dump(tree): v = cStringIO() Printer(file=v).visit(tree) return v.getvalue()
(tree)
39,233
astunparse
unparse
null
def unparse(tree): v = cStringIO() Unparser(tree, file=v) return v.getvalue()
(tree)
39,236
idna_ssl
patch_match_hostname
null
def patch_match_hostname(): if PY_370: return if hasattr(ssl.match_hostname, 'patched'): return ssl.match_hostname = patched_match_hostname ssl.match_hostname.patched = True
()
39,237
idna_ssl
patched_match_hostname
null
def patched_match_hostname(cert, hostname): try: hostname = idna.encode(hostname, uts46=True).decode('ascii') except UnicodeError: hostname = hostname.encode('idna').decode('ascii') return real_match_hostname(cert, hostname)
(cert, hostname)
39,238
ssl
match_hostname
Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed. The function matches IP addresses rather than dNSNames if hostname is a valid ipaddress string. IPv4 addresses are supported on all platforms. IPv6 addresses are supported on platforms with IPv6 support (AF_INET6 and inet_pton). CertificateError is raised on failure. On success, the function returns nothing.
def match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed. The function matches IP addresses rather than dNSNames if hostname is a valid ipaddress string. IPv4 addresses are supported on all platforms. IPv6 addresses are supported on platforms with IPv6 support (AF_INET6 and inet_pton). CertificateError is raised on failure. On success, the function returns nothing. """ warnings.warn( "ssl.match_hostname() is deprecated", category=DeprecationWarning, stacklevel=2 ) if not cert: raise ValueError("empty or no certificate, match_hostname needs a " "SSL socket or SSL context with either " "CERT_OPTIONAL or CERT_REQUIRED") try: host_ip = _inet_paton(hostname) except ValueError: # Not an IP address (common case) host_ip = None dnsnames = [] san = cert.get('subjectAltName', ()) for key, value in san: if key == 'DNS': if host_ip is None and _dnsname_match(value, hostname): return dnsnames.append(value) elif key == 'IP Address': if host_ip is not None and _ipaddress_match(value, host_ip): return dnsnames.append(value) if not dnsnames: # The subject is only checked when there is no dNSName entry # in subjectAltName for sub in cert.get('subject', ()): for key, value in sub: # XXX according to RFC 2818, the most specific Common Name # must be used. if key == 'commonName': if _dnsname_match(value, hostname): return dnsnames.append(value) if len(dnsnames) > 1: raise CertificateError("hostname %r " "doesn't match either of %s" % (hostname, ', '.join(map(repr, dnsnames)))) elif len(dnsnames) == 1: raise CertificateError("hostname %r " "doesn't match %r" % (hostname, dnsnames[0])) else: raise CertificateError("no appropriate commonName or " "subjectAltName fields were found")
(cert, hostname)
39,239
idna_ssl
reset_match_hostname
null
def reset_match_hostname(): if PY_370: return if not hasattr(ssl.match_hostname, 'patched'): return ssl.match_hostname = real_match_hostname
()
39,242
segno.encoder
DataOverflowError
Indicates a problem that the provided data does not fit into the provided QR Code version or the data is too large in general. This exception is inherited from :py:exc:`ValueError` and is only raised if the data does not fit into the provided (Micro) QR Code version. Basically it is sufficient to catch a :py:exc:`ValueError`.
class DataOverflowError(ValueError): """\ Indicates a problem that the provided data does not fit into the provided QR Code version or the data is too large in general. This exception is inherited from :py:exc:`ValueError` and is only raised if the data does not fit into the provided (Micro) QR Code version. Basically it is sufficient to catch a :py:exc:`ValueError`. """
null
39,243
segno
QRCode
Represents a (Micro) QR Code.
class QRCode: """\ Represents a (Micro) QR Code. """ __slots__ = ('matrix', 'mask', '_version', '_error', '_mode', '_matrix_size') def __init__(self, code): """\ Initializes the QR Code object. :param code: An object with a ``matrix``, ``version``, ``error``, ``mask`` and ``segments`` attribute. """ matrix = code.matrix self.matrix = matrix """Returns the matrix. :rtype: tuple of :py:class:`bytearray` instances. """ self.mask = code.mask """Returns the data mask pattern reference :rtype: int """ self._matrix_size = len(matrix[0]), len(matrix) self._version = code.version self._error = code.error self._mode = code.segments[0].mode if len(code.segments) == 1 else None @property def version(self): """\ (Micro) QR Code version. Either a string ("M1", "M2", "M3", "M4") or an integer in the range of 1 .. 40. :rtype: str or int """ return encoder.get_version_name(self._version) @property def error(self): """\ Error correction level; either a string ("L", "M", "Q", "H") or ``None`` if the QR code provides no error correction (Micro QR Code version M1) :rtype: str """ if self._error is None: return None return encoder.get_error_name(self._error) @property def mode(self): """\ String indicating the mode ("numeric", "alphanumeric", "byte", "kanji", or "hanzi"). May be ``None`` if multiple modes are used. :rtype: str or None """ if self._mode is not None: return encoder.get_mode_name(self._mode) return None @property def designator(self): """\ Returns the version and error correction level as string `V-E` where `V` represents the version number and `E` the error level. :rtype: str """ version = str(self.version) return '-'.join((version, self.error) if self.error else (version,)) @property def default_border_size(self): """\ Indicates the default border size aka quiet zone. QR Codes have a quiet zone of four light modules, while Micro QR Codes have a quiet zone of two light modules. :rtype: int """ return utils.get_default_border_size(self._matrix_size) @property def is_micro(self): """\ Indicates if this QR code is a Micro QR code :rtype: bool """ return self._version < 1 def __eq__(self, other): return self.__class__ == other.__class__ and self.matrix == other.matrix __hash__ = None def symbol_size(self, scale=1, border=None): """\ Returns the symbol size (width x height) with the provided border and scaling factor. :param scale: Indicates the size of a single module (default: 1). The size of a module depends on the used output format; i.e. in a PNG context, a scaling factor of 2 indicates that a module has a size of 2 x 2 pixel. Some outputs (i.e. SVG) accept floating point values. :type scale: int or float :param int border: The border size or ``None`` to specify the default quiet zone (4 for QR Codes, 2 for Micro QR Codes). :rtype: tuple (width, height) """ return utils.get_symbol_size(self._matrix_size, scale=scale, border=border) def matrix_iter(self, scale=1, border=None, verbose=False): """\ Returns an iterator over the matrix which includes the border. The border is returned as sequence of light modules. Dark modules are reported as ``0x1``, light modules have the value ``0x0``. The following example converts the QR code matrix into a list of lists which use boolean values for the modules (True = dark module, False = light module):: >>> import segno >>> qrcode = segno.make('The Beatles') >>> width, height = qrcode.symbol_size(scale=2) >>> res = [] >>> # Scaling factor 2, default border >>> for row in qrcode.matrix_iter(scale=2): >>> res.append([col == 0x1 for col in row]) >>> width == len(res[0]) True >>> height == len(res) True If `verbose` is ``True``, the iterator returns integer constants which indicate the type of the module, i.e. ``segno.consts.TYPE_FINDER_PATTERN_DARK``, ``segno.consts.TYPE_FINDER_PATTERN_LIGHT``, ``segno.consts.TYPE_QUIET_ZONE`` etc. To check if the returned module type is dark or light, use:: if mt >> 8: print('dark module') if not mt >> 8: print('light module') :param int scale: The scaling factor (default: ``1``). :param int border: The size of border / quiet zone or ``None`` to indicate the default border. :param bool verbose: Indicates if the type of the module should be returned instead of ``0x1`` and ``0x0`` values. See :py:mod:`segno.consts` for the return values. This feature is currently in EXPERIMENTAL state. :raises: :py:exc:`ValueError` if the scaling factor or the border is invalid (i.e. negative). """ iterfn = utils.matrix_iter_verbose if verbose else utils.matrix_iter return iterfn(self.matrix, self._matrix_size, scale, border) def show(self, delete_after=20, scale=10, border=None, dark='#000', light='#fff'): # pragma: no cover """\ Displays this QR code. This method is mainly intended for debugging purposes. This method saves the QR code as an image (by default with a scaling factor of 10) to a temporary file and opens it with the standard PNG viewer application or within the standard webbrowser. The temporary file is deleted afterwards (unless :paramref:`delete_after <segno.QRCode.show.delete_after>` is set to ``None``). If this method does not show any result, try to increase the :paramref:`delete_after <segno.QRCode.show.delete_after>` value or set it to ``None`` :param delete_after: Time in seconds to wait till the temporary file is deleted. :type delete_after: int or None :param int scale: Integer indicating the size of a single module. :param border: Integer indicating the size of the quiet zone. If set to ``None`` (default), the recommended border size will be used. :type border: int or None :param dark: The color of the dark modules (default: black). :param light: The color of the light modules (default: white). """ import os import time import tempfile import webbrowser import threading from urllib.parse import urljoin from urllib.request import pathname2url def delete_file(name): time.sleep(delete_after) try: os.unlink(name) except OSError: pass f = tempfile.NamedTemporaryFile('wb', suffix='.png', delete=False) try: self.save(f, scale=scale, dark=dark, light=light, border=border) except: # noqa: E722 f.close() os.unlink(f.name) raise f.close() webbrowser.open_new_tab(urljoin('file:', pathname2url(f.name))) if delete_after is not None: t = threading.Thread(target=delete_file, args=(f.name,)) t.start() def svg_data_uri(self, xmldecl=False, encode_minimal=False, omit_charset=False, nl=False, **kw): """\ Converts the QR code into an SVG data URI. The XML declaration is omitted by default (set :paramref:`xmldecl <segno.QRCode.svg_data_uri.xmldecl>` to ``True`` to enable it), further the newline is omitted by default (set ``nl`` to ``True`` to enable it). Aside from the missing `out` parameter, the different `xmldecl` and `nl` default values, and the additional parameters :paramref:`encode_minimal <segno.QRCode.svg_data_uri.encode_minimal>` and :paramref:`omit_charset <segno.QRCode.svg_data_uri.omit_charset>`, this method uses the same parameters as the usual SVG serializer, see :py:func:`save` and the available `SVG parameters <#svg>`_ .. note:: In order to embed a SVG image in HTML without generating a file, the :py:func:`svg_inline` method could serve better results, as it usually produces a smaller output. :param bool xmldecl: Indicates if the XML declaration should be serialized (default: ``False``) :param bool encode_minimal: Indicates if the resulting data URI should use minimal percent encoding (disabled by default). :param bool omit_charset: Indicates if the ``;charset=...`` should be omitted (disabled by default) :param bool nl: Indicates if the document should have a trailing newline (default: ``False``) :rtype: str """ return writers.as_svg_data_uri(self.matrix, self._matrix_size, xmldecl=xmldecl, nl=nl, encode_minimal=encode_minimal, omit_charset=omit_charset, **kw) def svg_inline(self, **kw): """\ Returns an SVG representation which is embeddable into HTML5 contexts. Due to the fact that HTML5 directly supports SVG, various elements of an SVG document can or should be suppressed (i.e. the XML declaration and the SVG namespace). This method returns a string that can be used in an HTML context. This method uses the same parameters as the usual SVG serializer, see :py:func:`save` and the available `SVG parameters <#svg>`_ (the ``out`` and ``kind`` parameters are not supported). The returned string can be used directly in `Jinja <https://jinja.palletsprojects.com/>`_ and `Django <https://www.djangoproject.com/>`_ templates, provided the ``safe`` filter is used which marks a string as not requiring further HTML escaping prior to output. :: <div>{{ qr.svg_inline(dark='#228b22', scale=3) | safe }}</div> :rtype: str """ buff = io.BytesIO() self.save(buff, kind='svg', xmldecl=False, svgns=False, nl=False, **kw) return buff.getvalue().decode(kw.get('encoding', 'utf-8')) def png_data_uri(self, **kw): """\ Converts the QR code into a PNG data URI. Uses the same keyword parameters as the usual PNG serializer, see :py:func:`save` and the available `PNG parameters <#png>`_ :rtype: str """ return writers.as_png_data_uri(self.matrix, self._matrix_size, **kw) def terminal(self, out=None, border=None, compact=False): """\ Serializes the matrix as ANSI escape code or Unicode Block Elements (if ``compact`` is ``True``). Under Windows, no ANSI escape sequence is generated but the Windows API is used *unless* :paramref:`out <segno.QRCode.terminal.out>` is a writable object or using WinAPI fails or if ``compact`` is ``True``. :param out: Filename or a file-like object supporting to write text. If ``None`` (default), the matrix is written to :py:class:`sys.stdout`. :param int border: Integer indicating the size of the quiet zone. If set to ``None`` (default), the recommended border size will be used (``4`` for QR Codes, ``2`` for Micro QR Codes). :param bool compact: Indicates if a more compact QR code should be shown (default: ``False``). """ if compact: writers.write_terminal_compact(self.matrix, self._matrix_size, out or sys.stdout, border) elif out is None and sys.platform == 'win32': # pragma: no cover # Windows < 10 does not support ANSI escape sequences, try to # call the a Windows specific terminal output which uses the # Windows API. try: writers.write_terminal_win(self.matrix, self._matrix_size, border) except OSError: # Use the standard output even if it may print garbage writers.write_terminal(self.matrix, self._matrix_size, sys.stdout, border) else: writers.write_terminal(self.matrix, self._matrix_size, out or sys.stdout, border) def save(self, out, kind=None, **kw): """\ Serializes the QR code in one of the supported formats. The serialization format depends on the filename extension. .. _common_keywords: **Common keywords** ========== ============================================================== Name Description ========== ============================================================== scale Integer or float indicating the size of a single module. Default: 1. The interpretation of the scaling factor depends on the serializer. For pixel-based output (like :ref:`PNG <png>`) the scaling factor is interpreted as pixel-size (1 = 1 pixel). :ref:`EPS <eps>` interprets ``1`` as 1 point (1/72 inch) per module. Some serializers (like :ref:`SVG <svg>`) accept float values. If the serializer does not accept float values, the value will be converted to an integer value (note: int(1.6) == 1). border Integer indicating the size of the quiet zone. If set to ``None`` (default), the recommended border size will be used (``4`` for QR codes, ``2`` for a Micro QR codes). A value of ``0`` indicates that border should be omitted. dark A string or tuple representing a color value for the dark modules. The default value is "black". The color can be provided as ``(R, G, B)`` tuple, as web color name (like "red") or in hexadecimal format (``#RGB`` or ``#RRGGBB``). Some serializers (i.e. :ref:`SVG <svg>` and :ref:`PNG <png>`) accept an alpha transparency value like ``#RRGGBBAA``. light A string or tuple representing a color for the light modules. See `dark` for valid values. The default value depends on the serializer. :ref:`SVG <svg>` uses no color (``None``) for light modules by default, other serializers, like :ref:`PNG <png>`, use "white" as default light color. ========== ============================================================== .. _module_colors: **Module Colors** =============== ======================================================= Name Description =============== ======================================================= finder_dark Color of the dark modules of the finder patterns Default: undefined, use value of "dark" finder_light Color of the light modules of the finder patterns Default: undefined, use value of "light" data_dark Color of the dark data modules Default: undefined, use value of "dark" data_light Color of the light data modules. Default: undefined, use value of "light". version_dark Color of the dark modules of the version information. Default: undefined, use value of "dark". version_light Color of the light modules of the version information, Default: undefined, use value of "light". format_dark Color of the dark modules of the format information. Default: undefined, use value of "dark". format_light Color of the light modules of the format information. Default: undefined, use value of "light". alignment_dark Color of the dark modules of the alignment patterns. Default: undefined, use value of "dark". alignment_light Color of the light modules of the alignment patterns. Default: undefined, use value of "light". timing_dark Color of the dark modules of the timing patterns. Default: undefined, use value of "dark". timing_light Color of the light modules of the timing patterns. Default: undefined, use value of "light". separator Color of the separator. Default: undefined, use value of "light". dark_module Color of the dark module (a single dark module which occurs in all QR Codes but not in Micro QR Codes. Default: undefined, use value of "dark". quiet_zone Color of the quiet zone / border. Default: undefined, use value of "light". =============== ======================================================= .. _svg: **Scalable Vector Graphics (SVG)** All :ref:`common keywords <common_keywords>` and :ref:`module colors <module_colors>` are supported. ================ ============================================================== Name Description ================ ============================================================== out Filename or :py:class:`io.BytesIO` kind "svg" or "svgz" (to create a gzip compressed SVG) scale integer or float dark Default: "#000" (black) ``None`` is a valid value. If set to ``None``, the resulting path won't have a "stroke" attribute. The "stroke" attribute may be defined via CSS (external). If an alpha channel is defined, the output depends of the used SVG version. For SVG versions >= 2.0, the "stroke" attribute will have a value like "rgba(R, G, B, A)", otherwise the path gets another attribute "stroke-opacity" to emulate the alpha channel. To minimize the document size, the SVG serializer uses automatically the shortest color representation: If a value like "#000000" is provided, the resulting document will have a color value of "#000". If the color is "#FF0000", the resulting color is not "#F00", but the web color name "red". light Default value ``None``. If this parameter is set to another value, the resulting image will have another path which is used to define the color of the light modules. If an alpha channel is used, the resulting path may have a "fill-opacity" attribute (for SVG version < 2.0) or the "fill" attribute has a "rgba(R, G, B, A)" value. xmldecl Boolean value (default: ``True``) indicating whether the document should have an XML declaration header. Set to ``False`` to omit the header. svgns Boolean value (default: ``True``) indicating whether the document should have an explicit SVG namespace declaration. Set to ``False`` to omit the namespace declaration. The latter might be useful if the document should be embedded into a HTML 5 document where the SVG namespace is implicitly defined. title String (default: ``None``) Optional title of the generated SVG document. desc String (default: ``None``) Optional description of the generated SVG document. svgid A string indicating the ID of the SVG document (if set to ``None`` (default), the SVG element won't have an ID). svgclass Default: "segno". The CSS class of the SVG document (if set to ``None``, the SVG element won't have a class). lineclass Default: "qrline". The CSS class of the path element (which draws the dark modules (if set to ``None``, the path won't have a class). omitsize Indicates if width and height attributes should be omitted (default: ``False``). If these attributes are omitted, a ``viewBox`` attribute will be added to the document. unit Default: ``None`` Indicates the unit for width / height and other coordinates. By default, the unit is unspecified and all values are in the user space. Valid values: em, ex, px, pt, pc, cm, mm, in, and percentages (any string is accepted, this parameter is not validated by the serializer) encoding Encoding of the XML document. "utf-8" by default. svgversion SVG version (default: ``None``). If specified (a float), the resulting document has an explicit "version" attribute. If set to ``None``, the document won't have a "version" attribute. This parameter is not validated. compresslevel Default: 9. This parameter is only valid, if a compressed SVG document should be created (file extension "svgz"). 1 is fastest and produces the least compression, 9 is slowest and produces the most. 0 is no compression. draw_transparent Indicates if transparent SVG paths should be added to the graphic (default: ``False``) nl Indicates if the document should have a trailing newline (default: ``True``) ================ ============================================================== .. _png: **Portable Network Graphics (PNG)** This writes either a grayscale (maybe with transparency) PNG (color type 0) or a palette-based (maybe with transparency) image (color type 3). If the dark / light values are ``None``, white or black, the serializer chooses the more compact grayscale mode, in all other cases a palette-based image is written. All :ref:`common keywords <common_keywords>` and :ref:`module colors <module_colors>` are supported. =============== ============================================================== Name Description =============== ============================================================== out Filename or :py:class:`io.BytesIO` kind "png" scale integer dark Default: "#000" (black) ``None`` is a valid value iff light is not ``None``. If set to ``None``, the dark modules become transparent. light Default value "#fff" (white) See keyword "dark" for further details. compresslevel Default: 9. Integer indicating the compression level for the ``IDAT`` (data) chunk. 1 is fastest and produces the least compression, 9 is slowest and produces the most. 0 is no compression. dpi Default: ``None``. Specifies the DPI value for the image. By default, the DPI value is unspecified. Please note that the DPI value is converted into meters (maybe with rounding errors) since PNG does not support the unit "dots per inch". =============== ============================================================== .. _eps: **Encapsulated PostScript (EPS)** All :ref:`common keywords <common_keywords>` are supported. ============= ============================================================== Name Description ============= ============================================================== out Filename or :py:class:`io.StringIO` kind "eps" scale integer or float dark Default: "#000" (black) light Default value: ``None`` (transparent light modules) ============= ============================================================== .. _pdf: **Portable Document Format (PDF)** All :ref:`common keywords <common_keywords>` are supported. ============= ============================================================== Name Description ============= ============================================================== out Filename or :py:class:`io.BytesIO` kind "pdf" scale integer or float dark Default: "#000" (black) light Default value: ``None`` (transparent light modules) compresslevel Default: 9. Integer indicating the compression level. 1 is fastest and produces the least compression, 9 is slowest and produces the most. 0 is no compression. ============= ============================================================== .. _txt: **Text (TXT)** Aside of "scale", all :ref:`common keywords <common_keywords>` are supported. ============= ============================================================== Name Description ============= ============================================================== out Filename or :py:class:`io.StringIO` kind "txt" dark Default: "1" light Default: "0" ============= ============================================================== .. _ansi: **ANSI escape code** Supports the "border" keyword, only! ============= ============================================================== Name Description ============= ============================================================== out Filename or :py:class:`io.StringIO` kind "ans" ============= ============================================================== .. _pbm: **Portable Bitmap (PBM)** All :ref:`common keywords <common_keywords>` are supported. ============= ============================================================== Name Description ============= ============================================================== out Filename or :py:class:`io.BytesIO` kind "pbm" scale integer plain Default: False. Boolean to switch between the P4 and P1 format. If set to ``True``, the (outdated) P1 serialization format is used. ============= ============================================================== .. _pam: **Portable Arbitrary Map (PAM)** All :ref:`common keywords <common_keywords>` are supported. ============= ============================================================== Name Description ============= ============================================================== out Filename or :py:class:`io.BytesIO` kind "pam" scale integer dark Default: "#000" (black). light Default value "#fff" (white). Use ``None`` for transparent light modules. ============= ============================================================== .. _ppm: **Portable Pixmap (PPM)** All :ref:`common keywords <common_keywords>` and :ref:`module colors <module_colors>` are supported. ============= ============================================================== Name Description ============= ============================================================== out Filename or :py:class:`io.BytesIO` kind "ppm" scale integer dark Default: "#000" (black). light Default value "#fff" (white). ============= ============================================================== .. _latex: **LaTeX / PGF/TikZ** To use the output of this serializer, the ``PGF/TikZ`` (and optionally ``hyperref``) package is required in the LaTeX environment. The serializer itself does not depend on any external packages. All :ref:`common keywords <common_keywords>` are supported. ============= ============================================================== Name Description ============= ============================================================== out Filename or :py:class:`io.StringIO` kind "tex" scale integer or float dark LaTeX color name (default: "black"). The color is written "at it is", please ensure that the color is a standard color or it has been defined in the enclosing LaTeX document. url Default: ``None``. Optional URL where the QR code should point to. Requires the ``hyperref`` package in the LaTeX environment. ============= ============================================================== .. _xbm: **X BitMap (XBM)** All :ref:`common keywords <common_keywords>` are supported. ============= ============================================================== Name Description ============= ============================================================== out Filename or :py:class:`io.StringIO` kind "xbm" scale integer name Name of the variable (default: "img") ============= ============================================================== .. _xpm: **X PixMap (XPM)** All :ref:`common keywords <common_keywords>` are supported. ============= ============================================================== Name Description ============= ============================================================== out Filename or :py:class:`io.StringIO` kind "xpm" scale integer dark Default: "#000" (black). ``None`` indicates transparent dark modules. light Default value "#fff" (white) ``None`` indicates transparent light modules. name Name of the variable (default: "img") ============= ============================================================== :param out: A filename or a writable file-like object with a ``name`` attribute. Use the :paramref:`kind <segno.QRCode.save.kind>` parameter if `out` is a :py:class:`io.BytesIO` or :py:class:`io.StringIO` stream which don't have a ``name`` attribute. :param str kind: Default ``None``. If the desired output format cannot be determined from the :paramref:`out <segno.QRCode.save.out>` parameter, this parameter can be used to indicate the serialization format (i.e. "svg" to enforce SVG output). The value is case insensitive. :param kw: Any of the supported keywords by the specific serializer. """ writers.save(self.matrix, self._matrix_size, out, kind, **kw) def __getattr__(self, name): """\ This is used to plug-in external serializers. When a "to_<name>" method is invoked, this method tries to find a ``segno.plugin.converter`` plugin with the provided ``<name>``. If such a plugin exists, a callable function is returned. The result of invoking the function depends on the plugin. """ if name.startswith('to_'): try: # Try to use the 3rd party lib first. This is required for # Python versions < 3.10 import importlib_metadata as metadata except ImportError: from importlib import metadata from functools import partial for ep in metadata.entry_points(group='segno.plugin.converter', name=name[3:]): plugin = ep.load() return partial(plugin, self) raise AttributeError('{0} object has no attribute {1}' .format(self.__class__, name))
(code)
39,244
segno
__eq__
null
def __eq__(self, other): return self.__class__ == other.__class__ and self.matrix == other.matrix
(self, other)
39,245
segno
__getattr__
This is used to plug-in external serializers. When a "to_<name>" method is invoked, this method tries to find a ``segno.plugin.converter`` plugin with the provided ``<name>``. If such a plugin exists, a callable function is returned. The result of invoking the function depends on the plugin.
def __getattr__(self, name): """\ This is used to plug-in external serializers. When a "to_<name>" method is invoked, this method tries to find a ``segno.plugin.converter`` plugin with the provided ``<name>``. If such a plugin exists, a callable function is returned. The result of invoking the function depends on the plugin. """ if name.startswith('to_'): try: # Try to use the 3rd party lib first. This is required for # Python versions < 3.10 import importlib_metadata as metadata except ImportError: from importlib import metadata from functools import partial for ep in metadata.entry_points(group='segno.plugin.converter', name=name[3:]): plugin = ep.load() return partial(plugin, self) raise AttributeError('{0} object has no attribute {1}' .format(self.__class__, name))
(self, name)