after_merge
stringlengths 28
79.6k
| before_merge
stringlengths 20
79.6k
| url
stringlengths 38
71
| full_traceback
stringlengths 43
922k
| traceback_type
stringclasses 555
values |
|---|---|---|---|---|
def from_lexer(cls, message, state, token):
lineno = None
colno = None
source = state.source
source_pos = token.getsourcepos()
if source_pos:
lineno = source_pos.lineno
colno = source_pos.colno
elif source:
# Use the end of the last line of source for `PrematureEndOfInput`.
# We get rid of empty lines and spaces so that the error matches
# with the last piece of visible code.
lines = source.rstrip().splitlines()
lineno = lineno or len(lines)
colno = colno or len(lines[lineno - 1])
else:
lineno = lineno or 1
colno = colno or 1
return cls(message, None, state.filename, source, lineno, colno)
|
def from_lexer(cls, message, state, token):
source_pos = token.getsourcepos()
if token.source_pos:
lineno = source_pos.lineno
colno = source_pos.colno
else:
lineno = -1
colno = -1
if state.source:
lines = state.source.splitlines()
if lines[-1] == "":
del lines[-1]
if lineno < 1:
lineno = len(lines)
if colno < 1:
colno = len(lines[-1])
source = lines[lineno - 1]
return cls(message, state.filename, lineno, colno, source)
|
https://github.com/hylang/hy/issues/1486
|
Traceback (most recent call last):
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval
_ast, expr = hy_compile(hytree, module_name, get_expr=True)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile
result = compiler.compile(tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do
return self._compile_branch(expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression
name)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression
body = self._compile_branch(expr)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression
body += self.compile(expr.pop(0))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile
raise_empty(HyCompileError, e, sys.exc_info()[2])
File "<string>", line 1, in raise_empty
hy.errors.HyCompileError: Internal Compiler Bug 😱
⤷ ImportError: cannot require names: [HySymbol('let')]
Compilation traceback:
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require
require(module, self.module_name, assignments=assignments)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require
raise ImportError("cannot require names: " + repr(list(unseen)))
|
hy.errors.HyCompileError
|
def error_handler(state, token):
tokentype = token.gettokentype()
if tokentype == "$end":
raise PrematureEndOfInput.from_lexer("Premature end of input", state, token)
else:
raise LexException.from_lexer(
"Ran into a %s where it wasn't expected." % tokentype, state, token
)
|
def error_handler(state, token):
tokentype = token.gettokentype()
if tokentype == "$end":
source_pos = token.source_pos or token.getsourcepos()
source = state.source
if source_pos:
lineno = source_pos.lineno
colno = source_pos.colno
else:
lineno = -1
colno = -1
raise PrematureEndOfInput.from_lexer("Premature end of input", state, token)
else:
raise LexException.from_lexer(
"Ran into a %s where it wasn't expected." % tokentype, state, token
)
|
https://github.com/hylang/hy/issues/1486
|
Traceback (most recent call last):
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval
_ast, expr = hy_compile(hytree, module_name, get_expr=True)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile
result = compiler.compile(tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do
return self._compile_branch(expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression
name)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression
body = self._compile_branch(expr)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression
body += self.compile(expr.pop(0))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile
raise_empty(HyCompileError, e, sys.exc_info()[2])
File "<string>", line 1, in raise_empty
hy.errors.HyCompileError: Internal Compiler Bug 😱
⤷ ImportError: cannot require names: [HySymbol('let')]
Compilation traceback:
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require
require(module, self.module_name, assignments=assignments)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require
raise ImportError("cannot require names: " + repr(list(unseen)))
|
hy.errors.HyCompileError
|
def macro(name):
"""Decorator to define a macro called `name`."""
name = mangle(name)
def _(fn):
fn = rename_function(fn, name)
try:
fn._hy_macro_pass_compiler = has_kwargs(fn)
except Exception:
# An exception might be raised if fn has arguments with
# names that are invalid in Python.
fn._hy_macro_pass_compiler = False
module = inspect.getmodule(fn)
module_macros = module.__dict__.setdefault("__macros__", {})
module_macros[name] = fn
return fn
return _
|
def macro(name):
"""Decorator to define a macro called `name`."""
name = mangle(name)
def _(fn):
fn.__name__ = "({})".format(name)
try:
fn._hy_macro_pass_compiler = has_kwargs(fn)
except Exception:
# An exception might be raised if fn has arguments with
# names that are invalid in Python.
fn._hy_macro_pass_compiler = False
module = inspect.getmodule(fn)
module_macros = module.__dict__.setdefault("__macros__", {})
module_macros[name] = fn
return fn
return _
|
https://github.com/hylang/hy/issues/1486
|
Traceback (most recent call last):
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval
_ast, expr = hy_compile(hytree, module_name, get_expr=True)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile
result = compiler.compile(tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do
return self._compile_branch(expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression
name)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression
body = self._compile_branch(expr)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression
body += self.compile(expr.pop(0))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile
raise_empty(HyCompileError, e, sys.exc_info()[2])
File "<string>", line 1, in raise_empty
hy.errors.HyCompileError: Internal Compiler Bug 😱
⤷ ImportError: cannot require names: [HySymbol('let')]
Compilation traceback:
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require
require(module, self.module_name, assignments=assignments)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require
raise ImportError("cannot require names: " + repr(list(unseen)))
|
hy.errors.HyCompileError
|
def _(fn):
fn = rename_function(fn, name)
try:
fn._hy_macro_pass_compiler = has_kwargs(fn)
except Exception:
# An exception might be raised if fn has arguments with
# names that are invalid in Python.
fn._hy_macro_pass_compiler = False
module = inspect.getmodule(fn)
module_macros = module.__dict__.setdefault("__macros__", {})
module_macros[name] = fn
return fn
|
def _(fn):
fn.__name__ = "({})".format(name)
try:
fn._hy_macro_pass_compiler = has_kwargs(fn)
except Exception:
# An exception might be raised if fn has arguments with
# names that are invalid in Python.
fn._hy_macro_pass_compiler = False
module = inspect.getmodule(fn)
module_macros = module.__dict__.setdefault("__macros__", {})
module_macros[name] = fn
return fn
|
https://github.com/hylang/hy/issues/1486
|
Traceback (most recent call last):
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval
_ast, expr = hy_compile(hytree, module_name, get_expr=True)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile
result = compiler.compile(tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do
return self._compile_branch(expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression
name)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression
body = self._compile_branch(expr)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression
body += self.compile(expr.pop(0))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile
raise_empty(HyCompileError, e, sys.exc_info()[2])
File "<string>", line 1, in raise_empty
hy.errors.HyCompileError: Internal Compiler Bug 😱
⤷ ImportError: cannot require names: [HySymbol('let')]
Compilation traceback:
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require
require(module, self.module_name, assignments=assignments)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require
raise ImportError("cannot require names: " + repr(list(unseen)))
|
hy.errors.HyCompileError
|
def tag(name):
"""Decorator to define a tag macro called `name`."""
def _(fn):
_name = mangle("#{}".format(name))
if not PY3:
_name = _name.encode("UTF-8")
fn = rename_function(fn, _name)
module = inspect.getmodule(fn)
module_name = module.__name__
if module_name.startswith("hy.core"):
module_name = None
module_tags = module.__dict__.setdefault("__tags__", {})
module_tags[mangle(name)] = fn
return fn
return _
|
def tag(name):
"""Decorator to define a tag macro called `name`."""
def _(fn):
_name = mangle("#{}".format(name))
if not PY3:
_name = _name.encode("UTF-8")
fn.__name__ = _name
module = inspect.getmodule(fn)
module_name = module.__name__
if module_name.startswith("hy.core"):
module_name = None
module_tags = module.__dict__.setdefault("__tags__", {})
module_tags[mangle(name)] = fn
return fn
return _
|
https://github.com/hylang/hy/issues/1486
|
Traceback (most recent call last):
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval
_ast, expr = hy_compile(hytree, module_name, get_expr=True)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile
result = compiler.compile(tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do
return self._compile_branch(expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression
name)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression
body = self._compile_branch(expr)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression
body += self.compile(expr.pop(0))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile
raise_empty(HyCompileError, e, sys.exc_info()[2])
File "<string>", line 1, in raise_empty
hy.errors.HyCompileError: Internal Compiler Bug 😱
⤷ ImportError: cannot require names: [HySymbol('let')]
Compilation traceback:
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require
require(module, self.module_name, assignments=assignments)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require
raise ImportError("cannot require names: " + repr(list(unseen)))
|
hy.errors.HyCompileError
|
def _(fn):
_name = mangle("#{}".format(name))
if not PY3:
_name = _name.encode("UTF-8")
fn = rename_function(fn, _name)
module = inspect.getmodule(fn)
module_name = module.__name__
if module_name.startswith("hy.core"):
module_name = None
module_tags = module.__dict__.setdefault("__tags__", {})
module_tags[mangle(name)] = fn
return fn
|
def _(fn):
_name = mangle("#{}".format(name))
if not PY3:
_name = _name.encode("UTF-8")
fn.__name__ = _name
module = inspect.getmodule(fn)
module_name = module.__name__
if module_name.startswith("hy.core"):
module_name = None
module_tags = module.__dict__.setdefault("__tags__", {})
module_tags[mangle(name)] = fn
return fn
|
https://github.com/hylang/hy/issues/1486
|
Traceback (most recent call last):
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval
_ast, expr = hy_compile(hytree, module_name, get_expr=True)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile
result = compiler.compile(tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do
return self._compile_branch(expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression
name)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression
body = self._compile_branch(expr)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression
body += self.compile(expr.pop(0))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile
raise_empty(HyCompileError, e, sys.exc_info()[2])
File "<string>", line 1, in raise_empty
hy.errors.HyCompileError: Internal Compiler Bug 😱
⤷ ImportError: cannot require names: [HySymbol('let')]
Compilation traceback:
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require
require(module, self.module_name, assignments=assignments)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require
raise ImportError("cannot require names: " + repr(list(unseen)))
|
hy.errors.HyCompileError
|
def require(source_module, target_module, assignments, prefix=""):
"""Load macros from one module into the namespace of another.
This function is called from the `require` special form in the compiler.
Parameters
----------
source_module: str or types.ModuleType
The module from which macros are to be imported.
target_module: str, types.ModuleType or None
The module into which the macros will be loaded. If `None`, then
the caller's namespace.
The latter is useful during evaluation of generated AST/bytecode.
assignments: str or list of tuples of strs
The string "ALL" or a list of macro name and alias pairs.
prefix: str, optional ("")
If nonempty, its value is prepended to the name of each imported macro.
This allows one to emulate namespaced macros, like
"mymacromodule.mymacro", which looks like an attribute of a module.
Returns
-------
out: boolean
Whether or not macros and tags were actually transferred.
"""
if target_module is None:
parent_frame = inspect.stack()[1][0]
target_namespace = parent_frame.f_globals
target_module = target_namespace.get("__name__", None)
elif isinstance(target_module, string_types):
target_module = importlib.import_module(target_module)
target_namespace = target_module.__dict__
elif inspect.ismodule(target_module):
target_namespace = target_module.__dict__
else:
raise HyTypeError(
"`target_module` is not a recognized type: {}".format(type(target_module))
)
# Let's do a quick check to make sure the source module isn't actually
# the module being compiled (e.g. when `runpy` executes a module's code
# in `__main__`).
# We use the module's underlying filename for this (when they exist), since
# it's the most "fixed" attribute.
if _same_modules(source_module, target_module):
return False
if not inspect.ismodule(source_module):
try:
source_module = importlib.import_module(source_module)
except ImportError as e:
reraise(HyRequireError, HyRequireError(e.args[0]), None)
source_macros = source_module.__dict__.setdefault("__macros__", {})
source_tags = source_module.__dict__.setdefault("__tags__", {})
if len(source_module.__macros__) + len(source_module.__tags__) == 0:
if assignments != "ALL":
raise HyRequireError(
"The module {} has no macros or tags".format(source_module)
)
else:
return False
target_macros = target_namespace.setdefault("__macros__", {})
target_tags = target_namespace.setdefault("__tags__", {})
if prefix:
prefix += "."
if assignments == "ALL":
name_assigns = [
(k, k) for k in tuple(source_macros.keys()) + tuple(source_tags.keys())
]
else:
name_assigns = assignments
for name, alias in name_assigns:
_name = mangle(name)
alias = mangle(prefix + alias)
if _name in source_module.__macros__:
target_macros[alias] = source_macros[_name]
elif _name in source_module.__tags__:
target_tags[alias] = source_tags[_name]
else:
raise HyRequireError(
"Could not require name {} from {}".format(_name, source_module)
)
return True
|
def require(source_module, target_module, assignments, prefix=""):
"""Load macros from one module into the namespace of another.
This function is called from the `require` special form in the compiler.
Parameters
----------
source_module: str or types.ModuleType
The module from which macros are to be imported.
target_module: str, types.ModuleType or None
The module into which the macros will be loaded. If `None`, then
the caller's namespace.
The latter is useful during evaluation of generated AST/bytecode.
assignments: str or list of tuples of strs
The string "ALL" or a list of macro name and alias pairs.
prefix: str, optional ("")
If nonempty, its value is prepended to the name of each imported macro.
This allows one to emulate namespaced macros, like
"mymacromodule.mymacro", which looks like an attribute of a module.
Returns
-------
out: boolean
Whether or not macros and tags were actually transferred.
"""
if target_module is None:
parent_frame = inspect.stack()[1][0]
target_namespace = parent_frame.f_globals
target_module = target_namespace.get("__name__", None)
elif isinstance(target_module, string_types):
target_module = importlib.import_module(target_module)
target_namespace = target_module.__dict__
elif inspect.ismodule(target_module):
target_namespace = target_module.__dict__
else:
raise TypeError(
"`target_module` is not a recognized type: {}".format(type(target_module))
)
# Let's do a quick check to make sure the source module isn't actually
# the module being compiled (e.g. when `runpy` executes a module's code
# in `__main__`).
# We use the module's underlying filename for this (when they exist), since
# it's the most "fixed" attribute.
if _same_modules(source_module, target_module):
return False
if not inspect.ismodule(source_module):
source_module = importlib.import_module(source_module)
source_macros = source_module.__dict__.setdefault("__macros__", {})
source_tags = source_module.__dict__.setdefault("__tags__", {})
if len(source_module.__macros__) + len(source_module.__tags__) == 0:
if assignments != "ALL":
raise ImportError(
"The module {} has no macros or tags".format(source_module)
)
else:
return False
target_macros = target_namespace.setdefault("__macros__", {})
target_tags = target_namespace.setdefault("__tags__", {})
if prefix:
prefix += "."
if assignments == "ALL":
name_assigns = [
(k, k) for k in tuple(source_macros.keys()) + tuple(source_tags.keys())
]
else:
name_assigns = assignments
for name, alias in name_assigns:
_name = mangle(name)
alias = mangle(prefix + alias)
if _name in source_module.__macros__:
target_macros[alias] = source_macros[_name]
elif _name in source_module.__tags__:
target_tags[alias] = source_tags[_name]
else:
raise ImportError(
"Could not require name {} from {}".format(_name, source_module)
)
return True
|
https://github.com/hylang/hy/issues/1486
|
Traceback (most recent call last):
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval
_ast, expr = hy_compile(hytree, module_name, get_expr=True)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile
result = compiler.compile(tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do
return self._compile_branch(expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression
name)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression
body = self._compile_branch(expr)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression
body += self.compile(expr.pop(0))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile
raise_empty(HyCompileError, e, sys.exc_info()[2])
File "<string>", line 1, in raise_empty
hy.errors.HyCompileError: Internal Compiler Bug 😱
⤷ ImportError: cannot require names: [HySymbol('let')]
Compilation traceback:
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require
require(module, self.module_name, assignments=assignments)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require
raise ImportError("cannot require names: " + repr(list(unseen)))
|
hy.errors.HyCompileError
|
def macro_exceptions(module, macro_tree, compiler=None):
try:
yield
except HyLanguageError as e:
# These are user-level Hy errors occurring in the macro.
# We want to pass them up to the user.
reraise(type(e), e, sys.exc_info()[2])
except Exception as e:
if compiler:
filename = compiler.filename
source = compiler.source
else:
filename = None
source = None
exc_msg = " ".join(
traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1])
)
msg = "expanding macro {}\n ".format(str(macro_tree[0]))
msg += exc_msg
reraise(
HyMacroExpansionError,
HyMacroExpansionError(msg, macro_tree, filename, source),
sys.exc_info()[2],
)
|
def macro_exceptions(module, macro_tree, compiler=None):
try:
yield
except Exception as e:
try:
filename = inspect.getsourcefile(module)
source = inspect.getsource(module)
except TypeError:
if compiler:
filename = compiler.filename
source = compiler.source
if not isinstance(e, HyTypeError):
exc_type = HyMacroExpansionError
msg = "expanding `{}': ".format(macro_tree[0])
msg += str(e).replace("<lambda>()", "", 1).strip()
else:
exc_type = HyTypeError
msg = e.message
reraise(
exc_type,
exc_type(msg, filename, macro_tree, source),
sys.exc_info()[2].tb_next,
)
|
https://github.com/hylang/hy/issues/1486
|
Traceback (most recent call last):
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval
_ast, expr = hy_compile(hytree, module_name, get_expr=True)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile
result = compiler.compile(tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do
return self._compile_branch(expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression
name)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression
body = self._compile_branch(expr)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression
body += self.compile(expr.pop(0))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile
raise_empty(HyCompileError, e, sys.exc_info()[2])
File "<string>", line 1, in raise_empty
hy.errors.HyCompileError: Internal Compiler Bug 😱
⤷ ImportError: cannot require names: [HySymbol('let')]
Compilation traceback:
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require
require(module, self.module_name, assignments=assignments)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require
raise ImportError("cannot require names: " + repr(list(unseen)))
|
hy.errors.HyCompileError
|
def macroexpand(tree, module, compiler=None, once=False):
"""Expand the toplevel macros for the given Hy AST tree.
Load the macros from the given `module`, then expand the (top-level) macros
in `tree` until we no longer can.
`HyExpression` resulting from macro expansions are assigned the module in
which the macro function is defined (determined using `inspect.getmodule`).
If the resulting `HyExpression` is itself macro expanded, then the
namespace of the assigned module is checked first for a macro corresponding
to the expression's head/car symbol. If the head/car symbol of such a
`HyExpression` is not found among the macros of its assigned module's
namespace, the outer-most namespace--e.g. the one given by the `module`
parameter--is used as a fallback.
Parameters
----------
tree: HyObject or list
Hy AST tree.
module: str or types.ModuleType
Module used to determine the local namespace for macros.
compiler: HyASTCompiler, optional
The compiler object passed to expanded macros.
once: boolean, optional
Only expand the first macro in `tree`.
Returns
------
out: HyObject
Returns a mutated tree with macros expanded.
"""
if not inspect.ismodule(module):
module = importlib.import_module(module)
assert not compiler or compiler.module == module
while True:
if not isinstance(tree, HyExpression) or tree == []:
break
fn = tree[0]
if fn in ("quote", "quasiquote") or not isinstance(fn, HySymbol):
break
fn = mangle(fn)
expr_modules = ([] if not hasattr(tree, "module") else [tree.module]) + [module]
# Choose the first namespace with the macro.
m = next(
(mod.__macros__[fn] for mod in expr_modules if fn in mod.__macros__), None
)
if not m:
break
opts = {}
if m._hy_macro_pass_compiler:
if compiler is None:
from hy.compiler import HyASTCompiler
compiler = HyASTCompiler(module)
opts["compiler"] = compiler
with macro_exceptions(module, tree, compiler):
obj = m(module.__name__, *tree[1:], **opts)
if isinstance(obj, HyExpression):
obj.module = inspect.getmodule(m)
tree = replace_hy_obj(obj, tree)
if once:
break
tree = wrap_value(tree)
return tree
|
def macroexpand(tree, module, compiler=None, once=False):
"""Expand the toplevel macros for the given Hy AST tree.
Load the macros from the given `module`, then expand the (top-level) macros
in `tree` until we no longer can.
`HyExpression` resulting from macro expansions are assigned the module in
which the macro function is defined (determined using `inspect.getmodule`).
If the resulting `HyExpression` is itself macro expanded, then the
namespace of the assigned module is checked first for a macro corresponding
to the expression's head/car symbol. If the head/car symbol of such a
`HyExpression` is not found among the macros of its assigned module's
namespace, the outer-most namespace--e.g. the one given by the `module`
parameter--is used as a fallback.
Parameters
----------
tree: HyObject or list
Hy AST tree.
module: str or types.ModuleType
Module used to determine the local namespace for macros.
compiler: HyASTCompiler, optional
The compiler object passed to expanded macros.
once: boolean, optional
Only expand the first macro in `tree`.
Returns
------
out: HyObject
Returns a mutated tree with macros expanded.
"""
if not inspect.ismodule(module):
module = importlib.import_module(module)
assert not compiler or compiler.module == module
while True:
if not isinstance(tree, HyExpression) or tree == []:
break
fn = tree[0]
if fn in ("quote", "quasiquote") or not isinstance(fn, HySymbol):
break
fn = mangle(fn)
expr_modules = ([] if not hasattr(tree, "module") else [tree.module]) + [module]
# Choose the first namespace with the macro.
m = next(
(mod.__macros__[fn] for mod in expr_modules if fn in mod.__macros__), None
)
if not m:
break
opts = {}
if m._hy_macro_pass_compiler:
if compiler is None:
from hy.compiler import HyASTCompiler
compiler = HyASTCompiler(module)
opts["compiler"] = compiler
with macro_exceptions(module, tree, compiler):
m_copy = make_empty_fn_copy(m)
m_copy(module.__name__, *tree[1:], **opts)
obj = m(module.__name__, *tree[1:], **opts)
if isinstance(obj, HyExpression):
obj.module = inspect.getmodule(m)
tree = replace_hy_obj(obj, tree)
if once:
break
tree = wrap_value(tree)
return tree
|
https://github.com/hylang/hy/issues/1486
|
Traceback (most recent call last):
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval
_ast, expr = hy_compile(hytree, module_name, get_expr=True)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile
result = compiler.compile(tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do
return self._compile_branch(expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression
name)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression
body = self._compile_branch(expr)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch
results = list(results)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker
return fn(self, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression
body += self.compile(expr.pop(0))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile
raise_empty(HyCompileError, e, sys.exc_info()[2])
File "<string>", line 1, in raise_empty
hy.errors.HyCompileError: Internal Compiler Bug 😱
⤷ ImportError: cannot require names: [HySymbol('let')]
Compilation traceback:
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile
ret = self.compile_atom(_type, tree)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom
else _compile_table[atom_type](self, atom))
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require
require(module, self.module_name, assignments=assignments)
File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require
raise ImportError("cannot require names: " + repr(list(unseen)))
|
hy.errors.HyCompileError
|
def mangle(s):
"""Stringify the argument and convert it to a valid Python identifier
according to Hy's mangling rules."""
def unicode_char_to_hex(uchr):
# Covert a unicode char to hex string, without prefix
if len(uchr) == 1 and ord(uchr) < 128:
return format(ord(uchr), "x")
return (
uchr.encode("unicode-escape")
.decode("utf-8")
.lstrip("\\U")
.lstrip("\\u")
.lstrip("\\x")
.lstrip("0")
)
assert s
s = str_type(s)
s = s.replace("-", "_")
s2 = s.lstrip("_")
leading_underscores = "_" * (len(s) - len(s2))
s = s2
if s.endswith("?"):
s = "is_" + s[:-1]
if not isidentifier(leading_underscores + s):
# Replace illegal characters with their Unicode character
# names, or hexadecimal if they don't have one.
s = "hyx_" + "".join(
c
if c != mangle_delim and isidentifier("S" + c)
# We prepend the "S" because some characters aren't
# allowed at the start of an identifier.
else "{0}{1}{0}".format(
mangle_delim,
unicodedata.name(c, "").lower().replace("-", "H").replace(" ", "_")
or "U{}".format(unicode_char_to_hex(c)),
)
for c in unicode_to_ucs4iter(s)
)
s = leading_underscores + s
assert isidentifier(s)
return s
|
def mangle(s):
"""Stringify the argument and convert it to a valid Python identifier
according to Hy's mangling rules."""
def unicode_char_to_hex(uchr):
# Covert a unicode char to hex string, without prefix
return (
uchr.encode("unicode-escape")
.decode("utf-8")
.lstrip("\\U")
.lstrip("\\u")
.lstrip("0")
)
assert s
s = str_type(s)
s = s.replace("-", "_")
s2 = s.lstrip("_")
leading_underscores = "_" * (len(s) - len(s2))
s = s2
if s.endswith("?"):
s = "is_" + s[:-1]
if not isidentifier(leading_underscores + s):
# Replace illegal characters with their Unicode character
# names, or hexadecimal if they don't have one.
s = "hyx_" + "".join(
c
if c != mangle_delim and isidentifier("S" + c)
# We prepend the "S" because some characters aren't
# allowed at the start of an identifier.
else "{0}{1}{0}".format(
mangle_delim,
unicodedata.name(c, "").lower().replace("-", "H").replace(" ", "_")
or "U{}".format(unicode_char_to_hex(c)),
)
for c in unicode_to_ucs4iter(s)
)
s = leading_underscores + s
assert isidentifier(s)
return s
|
https://github.com/hylang/hy/issues/1694
|
=> (mangle "\n")
'hyx_XUnX'
=> (unmangle (mangle "\n"))
Traceback (most recent call last):
…
ValueError: invalid literal for int() with base 16: 'n'
|
ValueError
|
def unicode_char_to_hex(uchr):
# Covert a unicode char to hex string, without prefix
if len(uchr) == 1 and ord(uchr) < 128:
return format(ord(uchr), "x")
return (
uchr.encode("unicode-escape")
.decode("utf-8")
.lstrip("\\U")
.lstrip("\\u")
.lstrip("\\x")
.lstrip("0")
)
|
def unicode_char_to_hex(uchr):
# Covert a unicode char to hex string, without prefix
return (
uchr.encode("unicode-escape")
.decode("utf-8")
.lstrip("\\U")
.lstrip("\\u")
.lstrip("0")
)
|
https://github.com/hylang/hy/issues/1694
|
=> (mangle "\n")
'hyx_XUnX'
=> (unmangle (mangle "\n"))
Traceback (most recent call last):
…
ValueError: invalid literal for int() with base 16: 'n'
|
ValueError
|
def __getattr__(self, name):
setattr(
Asty,
name,
staticmethod(
lambda x, **kwargs: getattr(ast, name)(
lineno=getattr(x, "start_line", getattr(x, "lineno", None)),
col_offset=getattr(x, "start_column", getattr(x, "col_offset", None)),
**kwargs,
)
),
)
return getattr(Asty, name)
|
def __getattr__(self, name):
setattr(
Asty,
name,
lambda self, x, **kwargs: getattr(ast, name)(
lineno=getattr(x, "start_line", getattr(x, "lineno", None)),
col_offset=getattr(x, "start_column", getattr(x, "col_offset", None)),
**kwargs,
),
)
return getattr(self, name)
|
https://github.com/hylang/hy/issues/588
|
=> (list-comp (do (print n) (print n)) [n [1 2]])
print(n)
[print(n) for n in [1L, 2L]]
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'n' is not defined
|
NameError
|
def compile_comprehension(self, expr, root, parts, final):
root = unmangle(ast_str(root))
node_class = {
"for": asty.For,
"lfor": asty.ListComp,
"dfor": asty.DictComp,
"sfor": asty.SetComp,
"gfor": asty.GeneratorExp,
}[root]
is_for = root == "for"
orel = []
if is_for:
# Get the `else`.
body, else_expr = final
if else_expr is not None:
orel.append(self._compile_branch(else_expr))
orel[0] += orel[0].expr_as_stmt()
else:
# Get the final value (and for dictionary
# comprehensions, the final key).
if node_class is asty.DictComp:
key, elt = map(self.compile, final)
else:
key = None
elt = self.compile(final)
# Compile the parts.
if is_for:
parts = parts[0]
if not parts:
return Result(
expr=ast.parse(
{
asty.For: "None",
asty.ListComp: "[]",
asty.DictComp: "{}",
asty.SetComp: "{1}.__class__()",
asty.GeneratorExp: "(_ for _ in [])",
}[node_class]
)
.body[0]
.value
)
parts = [
Tag(
p.tag,
self.compile(p.value)
if p.tag in ["if", "do"]
else [
self._storeize(p.value[0], self.compile(p.value[0])),
self.compile(p.value[1]),
],
)
for p in parts
]
# Produce a result.
if (
is_for
or elt.stmts
or (key is not None and key.stmts)
or any(
p.tag == "do"
or (p.value[1].stmts if p.tag in ("for", "afor", "setv") else p.value.stmts)
for p in parts
)
):
# The desired comprehension can't be expressed as a
# real Python comprehension. We'll write it as a nested
# loop in a function instead.
contains_yield = []
def f(parts):
# This function is called recursively to construct
# the nested loop.
if not parts:
if is_for:
if body:
bd = self._compile_branch(body)
if bd.contains_yield:
contains_yield.append(True)
return bd + bd.expr_as_stmt()
return Result(stmts=[asty.Pass(expr)])
if node_class is asty.DictComp:
ret = key + elt
val = asty.Tuple(
key, ctx=ast.Load(), elts=[key.force_expr, elt.force_expr]
)
else:
ret = elt
val = elt.force_expr
return ret + asty.Expr(elt, value=asty.Yield(elt, value=val))
(tagname, v), parts = parts[0], parts[1:]
if tagname in ("for", "afor"):
orelse = orel and orel.pop().stmts
node = asty.AsyncFor if tagname == "afor" else asty.For
return v[1] + node(
v[1],
target=v[0],
iter=v[1].force_expr,
body=f(parts).stmts,
orelse=orelse,
)
elif tagname == "setv":
return (
v[1]
+ asty.Assign(v[1], targets=[v[0]], value=v[1].force_expr)
+ f(parts)
)
elif tagname == "if":
return v + asty.If(v, test=v.force_expr, body=f(parts).stmts, orelse=[])
elif tagname == "do":
return v + v.expr_as_stmt() + f(parts)
else:
raise ValueError("can't happen")
if is_for:
ret = f(parts)
ret.contains_yield = bool(contains_yield)
return ret
fname = self.get_anon_var()
# Define the generator function.
ret = Result() + asty.FunctionDef(
expr,
name=fname,
args=ast.arguments(
args=[],
vararg=None,
kwarg=None,
kwonlyargs=[],
kw_defaults=[],
defaults=[],
),
body=f(parts).stmts,
decorator_list=[],
)
# Immediately call the new function. Unless the user asked
# for a generator, wrap the call in `[].__class__(...)` or
# `{}.__class__(...)` or `{1}.__class__(...)` to get the
# right type. We don't want to just use e.g. `list(...)`
# because the name `list` might be rebound.
return ret + Result(
expr=ast.parse(
"{}({}())".format(
{
asty.ListComp: "[].__class__",
asty.DictComp: "{}.__class__",
asty.SetComp: "{1}.__class__",
asty.GeneratorExp: "",
}[node_class],
fname,
)
)
.body[0]
.value
)
# We can produce a real comprehension.
generators = []
for tagname, v in parts:
if tagname in ("for", "afor"):
generators.append(
ast.comprehension(
target=v[0], iter=v[1].expr, ifs=[], is_async=int(tagname == "afor")
)
)
elif tagname == "setv":
generators.append(
ast.comprehension(
target=v[0],
iter=asty.Tuple(v[1], elts=[v[1].expr], ctx=ast.Load()),
ifs=[],
is_async=0,
)
)
elif tagname == "if":
generators[-1].ifs.append(v.expr)
else:
raise ValueError("can't happen")
if node_class is asty.DictComp:
return asty.DictComp(expr, key=key.expr, value=elt.expr, generators=generators)
return node_class(expr, elt=elt.expr, generators=generators)
|
def compile_comprehension(self, expr, form, expression, gen, cond):
# (list-comp expr [target iter] cond?)
if not isinstance(gen, HyList):
raise HyTypeError(gen, "Generator expression must be a list.")
gen_res, gen = self._compile_generator_iterables(
[gen] + ([] if cond is None else [cond])
)
if len(gen) == 0:
raise HyTypeError(expr, "Generator expression cannot be empty.")
ret = self.compile(expression)
node_class = (
asty.ListComp
if form == "list-comp"
else asty.SetComp
if form == "set-comp"
else asty.GeneratorExp
)
return ret + gen_res + node_class(expr, elt=ret.force_expr, generators=gen)
|
https://github.com/hylang/hy/issues/588
|
=> (list-comp (do (print n) (print n)) [n [1 2]])
print(n)
[print(n) for n in [1L, 2L]]
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'n' is not defined
|
NameError
|
def spoof_positions(obj):
if not isinstance(obj, HyObject):
return
if not hasattr(obj, "start_column"):
obj.start_column = 0
if not hasattr(obj, "start_line"):
obj.start_line = 0
if hasattr(obj, "__iter__") and not isinstance(obj, (string_types, bytes_type)):
for x in obj:
spoof_positions(x)
|
def spoof_positions(obj):
if not isinstance(obj, HyObject) or isinstance(obj, HyCons):
return
if not hasattr(obj, "start_column"):
obj.start_column = 0
if not hasattr(obj, "start_line"):
obj.start_line = 0
if hasattr(obj, "__iter__") and not isinstance(obj, (string_types, bytes_type)):
for x in obj:
spoof_positions(x)
|
https://github.com/hylang/hy/issues/568
|
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>
|
TypeError
|
def _render_quoted_form(self, form, level):
"""
Render a quoted form as a new HyExpression.
`level` is the level of quasiquoting of the current form. We can
unquote if level is 0.
Returns a three-tuple (`imports`, `expression`, `splice`).
The `splice` return value is used to mark `unquote-splice`d forms.
We need to distinguish them as want to concatenate them instead of
just nesting them.
"""
if level == 0:
if isinstance(form, HyExpression):
if form and form[0] in ("unquote", "unquote-splice"):
if len(form) != 2:
raise HyTypeError(
form, ("`%s' needs 1 argument, got %s" % form[0], len(form) - 1)
)
return set(), form[1], (form[0] == "unquote-splice")
if isinstance(form, HyExpression):
if form and form[0] == "quasiquote":
level += 1
if form and form[0] in ("unquote", "unquote-splice"):
level -= 1
name = form.__class__.__name__
imports = set([name])
if isinstance(form, (HyList, HyDict, HySet)):
if not form:
contents = HyList()
else:
# If there are arguments, they can be spliced
# so we build a sum...
contents = HyExpression([HySymbol("+"), HyList()])
for x in form:
f_imports, f_contents, splice = self._render_quoted_form(x, level)
imports.update(f_imports)
if splice:
to_add = HyExpression(
[
HySymbol("list"),
HyExpression([HySymbol("or"), f_contents, HyList()]),
]
)
else:
to_add = HyList([f_contents])
contents.append(to_add)
return imports, HyExpression([HySymbol(name), contents]).replace(form), False
elif isinstance(form, HySymbol):
return (
imports,
HyExpression([HySymbol(name), HyString(form)]).replace(form),
False,
)
elif isinstance(form, HyKeyword):
return imports, form, False
elif isinstance(form, HyString):
x = [HySymbol(name), form]
if form.brackets is not None:
x.extend([HyKeyword("brackets"), form.brackets])
return imports, HyExpression(x).replace(form), False
return imports, HyExpression([HySymbol(name), form]).replace(form), False
|
def _render_quoted_form(self, form, level):
"""
Render a quoted form as a new HyExpression.
`level` is the level of quasiquoting of the current form. We can
unquote if level is 0.
Returns a three-tuple (`imports`, `expression`, `splice`).
The `splice` return value is used to mark `unquote-splice`d forms.
We need to distinguish them as want to concatenate them instead of
just nesting them.
"""
if level == 0:
if isinstance(form, HyExpression):
if form and form[0] in ("unquote", "unquote-splice"):
if len(form) != 2:
raise HyTypeError(
form, ("`%s' needs 1 argument, got %s" % form[0], len(form) - 1)
)
return set(), form[1], (form[0] == "unquote-splice")
if isinstance(form, HyExpression):
if form and form[0] == "quasiquote":
level += 1
if form and form[0] in ("unquote", "unquote-splice"):
level -= 1
name = form.__class__.__name__
imports = set([name])
if isinstance(form, (HyList, HyDict, HySet)):
if not form:
contents = HyList()
else:
# If there are arguments, they can be spliced
# so we build a sum...
contents = HyExpression([HySymbol("+"), HyList()])
for x in form:
f_imports, f_contents, splice = self._render_quoted_form(x, level)
imports.update(f_imports)
if splice:
to_add = HyExpression(
[
HySymbol("list"),
HyExpression([HySymbol("or"), f_contents, HyList()]),
]
)
else:
to_add = HyList([f_contents])
contents.append(to_add)
return imports, HyExpression([HySymbol(name), contents]).replace(form), False
elif isinstance(form, HyCons):
ret = HyExpression([HySymbol(name)])
nimport, contents, splice = self._render_quoted_form(form.car, level)
if splice:
raise HyTypeError(form, "Can't splice dotted lists yet")
imports.update(nimport)
ret.append(contents)
nimport, contents, splice = self._render_quoted_form(form.cdr, level)
if splice:
raise HyTypeError(form, "Can't splice the cdr of a cons")
imports.update(nimport)
ret.append(contents)
return imports, ret.replace(form), False
elif isinstance(form, HySymbol):
return (
imports,
HyExpression([HySymbol(name), HyString(form)]).replace(form),
False,
)
elif isinstance(form, HyKeyword):
return imports, form, False
elif isinstance(form, HyString):
x = [HySymbol(name), form]
if form.brackets is not None:
x.extend([HyKeyword("brackets"), form.brackets])
return imports, HyExpression(x).replace(form), False
return imports, HyExpression([HySymbol(name), form]).replace(form), False
|
https://github.com/hylang/hy/issues/568
|
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>
|
TypeError
|
def paren(p):
return HyExpression(p[1])
|
def paren(p):
cont = p[1]
# Dotted lists are expressions of the form
# (a b c . d)
# that evaluate to nested cons cells of the form
# (a . (b . (c . d)))
if len(cont) >= 3 and isinstance(cont[-2], HySymbol) and cont[-2] == ".":
reject_spurious_dots(cont[:-2], cont[-1:])
if len(cont) == 3:
# Two-item dotted list: return the cons cell directly
return HyCons(cont[0], cont[2])
else:
# Return a nested cons cell
return HyCons(cont[0], paren([p[0], cont[1:], p[2]]))
# Warn preemptively on a malformed dotted list.
# Only check for dots after the first item to allow for a potential
# attribute accessor shorthand
reject_spurious_dots(cont[1:])
return HyExpression(p[1])
|
https://github.com/hylang/hy/issues/568
|
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>
|
TypeError
|
def replace(self, other):
for x in self:
replace_hy_obj(x, other)
HyObject.replace(self, other)
return self
|
def replace(self, other):
if self.car is not None:
replace_hy_obj(self.car, other)
if self.cdr is not None:
replace_hy_obj(self.cdr, other)
HyObject.replace(self, other)
|
https://github.com/hylang/hy/issues/568
|
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>
|
TypeError
|
def __repr__(self):
return str(self) if PRETTY else super(HyList, self).__repr__()
|
def __repr__(self):
if PRETTY:
return str(self)
else:
return "HyCons({}, {})".format(repr(self.car), repr(self.cdr))
|
https://github.com/hylang/hy/issues/568
|
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>
|
TypeError
|
def __new__(cls, real, imag=0, *args, **kwargs):
if isinstance(real, string_types):
value = super(HyComplex, cls).__new__(cls, strip_digit_separators(real))
p1, _, p2 = real.lstrip("+-").replace("-", "+").partition("+")
check_inf_nan_cap(p1, value.imag if "j" in p1 else value.real)
if p2:
check_inf_nan_cap(p2, value.imag)
return value
return super(HyComplex, cls).__new__(cls, real, imag)
|
def __new__(cls, car, cdr):
if isinstance(cdr, list):
# Keep unquotes in the cdr of conses
if type(cdr) == HyExpression:
if len(cdr) > 0 and type(cdr[0]) == HySymbol:
if cdr[0] in ("unquote", "unquote-splice"):
return super(HyCons, cls).__new__(cls)
return cdr.__class__([wrap_value(car)] + cdr)
elif cdr is None:
return HyExpression([wrap_value(car)])
else:
return super(HyCons, cls).__new__(cls)
|
https://github.com/hylang/hy/issues/568
|
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>
|
TypeError
|
def __init__(self, value):
self.name = value
|
def __init__(self, car, cdr):
self.car = wrap_value(car)
self.cdr = wrap_value(cdr)
|
https://github.com/hylang/hy/issues/568
|
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>
|
TypeError
|
def __str__(self):
with pretty():
g = colored.green
if self:
pairs = []
for k, v in zip(self[::2], self[1::2]):
k, v = repr_indent(k), repr_indent(v)
pairs.append(
("{0}{c}\n {1}\n " if "\n" in k + v else "{0}{c} {1}").format(
k, v, c=g(",")
)
)
if len(self) % 2 == 1:
pairs.append("{} {}\n".format(repr_indent(self[-1]), g("# odd")))
return "{}\n {}{}".format(
g("HyDict(["), ("{c}\n ".format(c=g(",")).join(pairs)), g("])")
)
else:
return "" + g("HyDict()")
|
def __str__(self):
with pretty():
c = colored.yellow
lines = ["" + c("<HyCons (")]
while True:
lines.append(" " + repr_indent(self.car))
if not isinstance(self.cdr, HyCons):
break
self = self.cdr
lines.append("{} {}{}".format(c("."), repr_indent(self.cdr), c(")>")))
return "\n".join(lines)
|
https://github.com/hylang/hy/issues/568
|
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>
|
TypeError
|
def __eq__(self, other):
if not isinstance(other, HyKeyword):
return NotImplemented
return self.name == other.name
|
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and self.car == other.car
and self.cdr == other.cdr
)
|
https://github.com/hylang/hy/issues/568
|
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>
|
TypeError
|
def __getitem__(self, item):
ret = super(HyList, self).__getitem__(item)
if isinstance(item, slice):
return self.__class__(ret)
return ret
|
def __getitem__(self, n):
if n == 0:
return self.car
if n == slice(1, None):
return self.cdr
raise IndexError("Can only get the car ([0]) or the cdr ([1:]) of a HyCons")
|
https://github.com/hylang/hy/issues/568
|
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>
|
TypeError
|
def runsource(self, source, filename="<input>", symbol="single"):
global SIMPLE_TRACEBACKS
try:
try:
do = import_buffer_to_hst(source)
except PrematureEndOfInput:
return True
except LexException as e:
if e.source is None:
e.source = source
e.filename = filename
print(e, file=sys.stderr)
return False
try:
def ast_callback(main_ast, expr_ast):
if self.spy:
# Mush the two AST chunks into a single module for
# conversion into Python.
new_ast = ast.Module(main_ast.body + [ast.Expr(expr_ast.body)])
print(astor.to_source(new_ast))
value = hy_eval(do, self.locals, "__console__", ast_callback)
except HyTypeError as e:
if e.source is None:
e.source = source
e.filename = filename
if SIMPLE_TRACEBACKS:
print(e, file=sys.stderr)
else:
self.showtraceback()
return False
except Exception:
self.showtraceback()
return False
if value is not None:
# Make the last non-None value available to
# the user as `_`.
self.locals["_"] = value
# Print the value.
try:
output = self.output_fn(value)
except Exception:
self.showtraceback()
return False
print(output)
return False
|
def runsource(self, source, filename="<input>", symbol="single"):
global SIMPLE_TRACEBACKS
try:
try:
do = import_buffer_to_hst(source)
except PrematureEndOfInput:
return True
except LexException as e:
if e.source is None:
e.source = source
e.filename = filename
print(e, file=sys.stderr)
return False
try:
def ast_callback(main_ast, expr_ast):
if self.spy:
# Mush the two AST chunks into a single module for
# conversion into Python.
new_ast = ast.Module(main_ast.body + [ast.Expr(expr_ast.body)])
print(astor.to_source(new_ast))
value = hy_eval(do, self.locals, "__console__", ast_callback)
except HyTypeError as e:
if e.source is None:
e.source = source
e.filename = filename
if SIMPLE_TRACEBACKS:
print(e, file=sys.stderr)
else:
self.showtraceback()
return False
except Exception:
self.showtraceback()
return False
if value is not None:
# Make the last non-None value available to
# the user as `_`.
self.locals["_"] = value
# Print the value.
print(self.output_fn(value))
return False
|
https://github.com/hylang/hy/issues/1389
|
=> (defclass BadRepr[] (defn __repr__ [self] (/ 0)))
class BadRepr:
def __repr__(self):
return (1 / 0)
None
=> (BadRepr)
BadRepr()
Traceback (most recent call last):
File "C:\Users\ME\workspace\hy36-gilch\Scripts\hy-script.py", line 11, in <module>
load_entry_point('hy', 'console_scripts', 'hy')()
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 341, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 336, in cmdline_handler
return run_repl(spy=options.spy, output_fn=options.repl_output_fn)
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 231, in run_repl
os=platform.system()
File "C:\Users\ME\AppData\Local\Programs\Python\Python36\lib\code.py", line 233, in interact
more = self.push(line)
File "C:\Users\ME\AppData\Local\Programs\Python\Python36\lib\code.py", line 259, in push
more = self.runsource(source, self.filename)
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 118, in runsource
print(self.output_fn(value))
File "<eval_body>", line 1, in __repr__
ZeroDivisionError: division by zero
(hy36-gilch) C:\Users\ME\Documents\GitHub\hy>
|
ZeroDivisionError
|
def runsource(self, source, filename="<input>", symbol="single"):
global SIMPLE_TRACEBACKS
try:
try:
do = import_buffer_to_hst(source)
except PrematureEndOfInput:
return True
except LexException as e:
if e.source is None:
e.source = source
e.filename = filename
print(e, file=sys.stderr)
return False
try:
def ast_callback(main_ast, expr_ast):
if self.spy:
# Mush the two AST chunks into a single module for
# conversion into Python.
new_ast = ast.Module(main_ast.body + [ast.Expr(expr_ast.body)])
print(astor.to_source(new_ast))
value = hy_eval(do, self.locals, "__console__", ast_callback)
except HyTypeError as e:
if e.source is None:
e.source = source
e.filename = filename
if SIMPLE_TRACEBACKS:
print(e, file=sys.stderr)
else:
self.showtraceback()
return False
except Exception:
self.showtraceback()
return False
if value is not None:
# Make the last non-None value available to
# the user as `_`.
self.locals["_"] = value
# Print the value.
print(self.output_fn(value))
return False
|
def runsource(self, source, filename="<input>", symbol="single"):
global SIMPLE_TRACEBACKS
try:
try:
tokens = tokenize(source)
except PrematureEndOfInput:
return True
do = HyExpression([HySymbol("do")] + tokens)
do.start_line = do.end_line = do.start_column = do.end_column = 1
do.replace(do)
except LexException as e:
if e.source is None:
e.source = source
e.filename = filename
print(e, file=sys.stderr)
return False
try:
def ast_callback(main_ast, expr_ast):
if self.spy:
# Mush the two AST chunks into a single module for
# conversion into Python.
new_ast = ast.Module(main_ast.body + [ast.Expr(expr_ast.body)])
print(astor.to_source(new_ast))
value = hy_eval(do, self.locals, "__console__", ast_callback)
except HyTypeError as e:
if e.source is None:
e.source = source
e.filename = filename
if SIMPLE_TRACEBACKS:
print(e, file=sys.stderr)
else:
self.showtraceback()
return False
except Exception:
self.showtraceback()
return False
if value is not None:
# Make the last non-None value available to
# the user as `_`.
self.locals["_"] = value
# Print the value.
print(self.output_fn(value))
return False
|
https://github.com/hylang/hy/issues/1174
|
=> (import numpy)
=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)
|
TypeError
|
def imports_as_stmts(self, expr):
"""Convert the Result's imports to statements"""
ret = Result()
for module, names in self.imports.items():
if None in names:
e = HyExpression(
[
HySymbol("import"),
HySymbol(module),
]
).replace(expr)
spoof_positions(e)
ret += self.compile(e)
names = sorted(name for name in names if name)
if names:
e = HyExpression(
[
HySymbol("import"),
HyList(
[HySymbol(module), HyList([HySymbol(name) for name in names])]
),
]
).replace(expr)
spoof_positions(e)
ret += self.compile(e)
self.imports = defaultdict(set)
return ret.stmts
|
def imports_as_stmts(self, expr):
"""Convert the Result's imports to statements"""
ret = Result()
for module, names in self.imports.items():
if None in names:
ret += self.compile(
[
HyExpression(
[
HySymbol("import"),
HySymbol(module),
]
).replace(expr)
]
)
names = sorted(name for name in names if name)
if names:
ret += self.compile(
[
HyExpression(
[
HySymbol("import"),
HyList(
[
HySymbol(module),
HyList([HySymbol(name) for name in names]),
]
),
]
).replace(expr)
]
)
self.imports = defaultdict(set)
return ret.stmts
|
https://github.com/hylang/hy/issues/1174
|
=> (import numpy)
=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)
|
TypeError
|
def compile_atom(self, atom_type, atom):
if atom_type in _compile_table:
ret = _compile_table[atom_type](self, atom)
if not isinstance(ret, Result):
ret = Result() + ret
return ret
if not isinstance(atom, HyObject):
atom = wrap_value(atom)
if isinstance(atom, HyObject):
spoof_positions(atom)
return self.compile_atom(type(atom), atom)
|
def compile_atom(self, atom_type, atom):
if atom_type in _compile_table:
ret = _compile_table[atom_type](self, atom)
if not isinstance(ret, Result):
ret = Result() + ret
return ret
|
https://github.com/hylang/hy/issues/1174
|
=> (import numpy)
=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)
|
TypeError
|
def _compile_maths_expression(self, expression):
ops = {
"+": ast.Add,
"/": ast.Div,
"//": ast.FloorDiv,
"*": ast.Mult,
"-": ast.Sub,
"%": ast.Mod,
"**": ast.Pow,
"<<": ast.LShift,
">>": ast.RShift,
"|": ast.BitOr,
"^": ast.BitXor,
"&": ast.BitAnd,
}
if PY35:
ops.update({"@": ast.MatMult})
op = ops[expression.pop(0)]
right_associative = op == ast.Pow
lineno, col_offset = expression.start_line, expression.start_column
if right_associative:
expression = expression[::-1]
ret = self.compile(expression.pop(0))
for child in expression:
left_expr = ret.force_expr
ret += self.compile(child)
right_expr = ret.force_expr
if right_associative:
left_expr, right_expr = right_expr, left_expr
ret += ast.BinOp(
left=left_expr,
op=op(),
right=right_expr,
lineno=lineno,
col_offset=col_offset,
)
return ret
|
def _compile_maths_expression(self, expression):
ops = {
"+": ast.Add,
"/": ast.Div,
"//": ast.FloorDiv,
"*": ast.Mult,
"-": ast.Sub,
"%": ast.Mod,
"**": ast.Pow,
"<<": ast.LShift,
">>": ast.RShift,
"|": ast.BitOr,
"^": ast.BitXor,
"&": ast.BitAnd,
}
if PY35:
ops.update({"@": ast.MatMult})
op = ops[expression.pop(0)]
right_associative = op == ast.Pow
if right_associative:
expression = expression[::-1]
ret = self.compile(expression.pop(0))
for child in expression:
left_expr = ret.force_expr
ret += self.compile(child)
right_expr = ret.force_expr
if right_associative:
left_expr, right_expr = right_expr, left_expr
ret += ast.BinOp(
left=left_expr,
op=op(),
right=right_expr,
lineno=child.start_line,
col_offset=child.start_column,
)
return ret
|
https://github.com/hylang/hy/issues/1174
|
=> (import numpy)
=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)
|
TypeError
|
def hy_compile(tree, module_name, root=ast.Module, get_expr=False):
"""
Compile a HyObject tree into a Python AST Module.
If `get_expr` is True, return a tuple (module, last_expression), where
`last_expression` is the.
"""
body = []
expr = None
if not isinstance(tree, HyObject):
tree = wrap_value(tree)
if not isinstance(tree, HyObject):
raise HyCompileError(
"`tree` must be a HyObject or capable of being promoted to one"
)
spoof_positions(tree)
compiler = HyASTCompiler(module_name)
result = compiler.compile(tree)
expr = result.force_expr
if not get_expr:
result += result.expr_as_stmt()
body = compiler.imports_as_stmts(tree) + result.stmts
ret = root(body=body)
if get_expr:
expr = ast.Expression(body=expr)
ret = (ret, expr)
return ret
|
def hy_compile(tree, module_name, root=ast.Module, get_expr=False):
"""
Compile a HyObject tree into a Python AST Module.
If `get_expr` is True, return a tuple (module, last_expression), where
`last_expression` is the.
"""
body = []
expr = None
if not (isinstance(tree, HyObject) or type(tree) is list):
raise HyCompileError("tree must be a HyObject or a list")
if isinstance(tree, HyObject) or tree:
compiler = HyASTCompiler(module_name)
result = compiler.compile(tree)
expr = result.force_expr
if not get_expr:
result += result.expr_as_stmt()
# We need to test that the type is *exactly* `list` because we don't
# want to do `tree[0]` on HyList or such.
spoof_tree = tree[0] if type(tree) is list else tree
body = compiler.imports_as_stmts(spoof_tree) + result.stmts
ret = root(body=body)
if get_expr:
expr = ast.Expression(body=expr)
ret = (ret, expr)
return ret
|
https://github.com/hylang/hy/issues/1174
|
=> (import numpy)
=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)
|
TypeError
|
def import_buffer_to_hst(buf):
"""Import content from buf and return a Hy AST."""
return HyExpression([HySymbol("do")] + tokenize(buf + "\n"))
|
def import_buffer_to_hst(buf):
"""Import content from buf and return a Hy AST."""
return tokenize(buf + "\n")
|
https://github.com/hylang/hy/issues/1174
|
=> (import numpy)
=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)
|
TypeError
|
def hy_eval(hytree, namespace=None, module_name=None, ast_callback=None):
"""``eval`` evaluates a quoted expression and returns the value. The optional
second and third arguments specify the dictionary of globals to use and the
module name. The globals dictionary defaults to ``(local)`` and the module
name defaults to the name of the current module.
=> (eval '(print "Hello World"))
"Hello World"
If you want to evaluate a string, use ``read-str`` to convert it to a
form first:
=> (eval (read-str "(+ 1 1)"))
2"""
if namespace is None:
frame = inspect.stack()[1][0]
namespace = inspect.getargvalues(frame).locals
if module_name is None:
m = inspect.getmodule(inspect.stack()[1][0])
module_name = "__eval__" if m is None else m.__name__
foo = HyObject()
foo.start_line = 0
foo.end_line = 0
foo.start_column = 0
foo.end_column = 0
replace_hy_obj(hytree, foo)
if not isinstance(module_name, string_types):
raise HyTypeError(foo, "Module name must be a string")
_ast, expr = hy_compile(hytree, module_name, get_expr=True)
# Spoof the positions in the generated ast...
for node in ast.walk(_ast):
node.lineno = 1
node.col_offset = 1
for node in ast.walk(expr):
node.lineno = 1
node.col_offset = 1
if ast_callback:
ast_callback(_ast, expr)
if not isinstance(namespace, dict):
raise HyTypeError(foo, "Globals must be a dictionary")
# Two-step eval: eval() the body of the exec call
eval(ast_compile(_ast, "<eval_body>", "exec"), namespace)
# Then eval the expression context and return that
return eval(ast_compile(expr, "<eval>", "eval"), namespace)
|
def hy_eval(hytree, namespace, module_name, ast_callback=None):
foo = HyObject()
foo.start_line = 0
foo.end_line = 0
foo.start_column = 0
foo.end_column = 0
replace_hy_obj(hytree, foo)
if not isinstance(module_name, string_types):
raise HyTypeError(foo, "Module name must be a string")
_ast, expr = hy_compile(hytree, module_name, get_expr=True)
# Spoof the positions in the generated ast...
for node in ast.walk(_ast):
node.lineno = 1
node.col_offset = 1
for node in ast.walk(expr):
node.lineno = 1
node.col_offset = 1
if ast_callback:
ast_callback(_ast, expr)
if not isinstance(namespace, dict):
raise HyTypeError(foo, "Globals must be a dictionary")
# Two-step eval: eval() the body of the exec call
eval(ast_compile(_ast, "<eval_body>", "exec"), namespace)
# Then eval the expression context and return that
return eval(ast_compile(expr, "<eval>", "eval"), namespace)
|
https://github.com/hylang/hy/issues/1174
|
=> (import numpy)
=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)
|
TypeError
|
def macroexpand_1(tree, compiler):
"""Expand the toplevel macro from `tree` once, in the context of
`module_name`."""
if isinstance(tree, HyExpression):
if tree == []:
return tree
fn = tree[0]
if fn in ("quote", "quasiquote"):
return tree
ntree = HyExpression(tree[:])
ntree.replace(tree)
opts = {}
if isinstance(fn, HyString):
m = _hy_macros[compiler.module_name].get(fn)
if m is None:
m = _hy_macros[None].get(fn)
if m is not None:
if m._hy_macro_pass_compiler:
opts["compiler"] = compiler
try:
m_copy = make_empty_fn_copy(m)
m_copy(*ntree[1:], **opts)
except TypeError as e:
msg = "expanding `" + str(tree[0]) + "': "
msg += str(e).replace("<lambda>()", "", 1).strip()
raise HyMacroExpansionError(tree, msg)
try:
obj = m(*ntree[1:], **opts)
except HyTypeError as e:
if e.expression is None:
e.expression = tree
raise
except Exception as e:
msg = "expanding `" + str(tree[0]) + "': " + repr(e)
raise HyMacroExpansionError(tree, msg)
replace_hy_obj(obj, tree)
return obj
return ntree
return tree
|
def macroexpand_1(tree, compiler):
"""Expand the toplevel macro from `tree` once, in the context of
`module_name`."""
if isinstance(tree, HyExpression):
if tree == []:
return tree
fn = tree[0]
if fn in ("quote", "quasiquote"):
return tree
ntree = HyExpression(tree[:])
ntree.replace(tree)
opts = {}
if isinstance(fn, HyString):
m = _hy_macros[compiler.module_name].get(fn)
if m is None:
m = _hy_macros[None].get(fn)
if m is not None:
if m._hy_macro_pass_compiler:
opts["compiler"] = compiler
try:
m_copy = make_empty_fn_copy(m)
m_copy(*ntree[1:], **opts)
except TypeError as e:
msg = "expanding `" + str(tree[0]) + "': "
msg += str(e).replace("<lambda>()", "", 1).strip()
raise HyMacroExpansionError(tree, msg)
try:
obj = wrap_value(m(*ntree[1:], **opts))
except HyTypeError as e:
if e.expression is None:
e.expression = tree
raise
except Exception as e:
msg = "expanding `" + str(tree[0]) + "': " + repr(e)
raise HyMacroExpansionError(tree, msg)
replace_hy_obj(obj, tree)
return obj
return ntree
return tree
|
https://github.com/hylang/hy/issues/1174
|
=> (import numpy)
=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)
|
TypeError
|
def tag_macroexpand(tag, tree, compiler):
"""Expand the tag macro "tag" with argument `tree`."""
load_macros(compiler.module_name)
tag_macro = _hy_tag[compiler.module_name].get(tag)
if tag_macro is None:
try:
tag_macro = _hy_tag[None][tag]
except KeyError:
raise HyTypeError(tag, "`{0}' is not a defined tag macro.".format(tag))
expr = tag_macro(tree)
return replace_hy_obj(expr, tree)
|
def tag_macroexpand(tag, tree, compiler):
"""Expand the tag macro "tag" with argument `tree`."""
load_macros(compiler.module_name)
tag_macro = _hy_tag[compiler.module_name].get(tag)
if tag_macro is None:
try:
tag_macro = _hy_tag[None][tag]
except KeyError:
raise HyTypeError(tag, "`{0}' is not a defined tag macro.".format(tag))
expr = tag_macro(tree)
return replace_hy_obj(wrap_value(expr), tree)
|
https://github.com/hylang/hy/issues/1174
|
=> (import numpy)
=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)
|
TypeError
|
def tokenize(buf):
"""
Tokenize a Lisp file or string buffer into internal Hy objects.
"""
try:
return parser.parse(lexer.lex(buf))
except LexingError as e:
pos = e.getsourcepos()
raise LexException(
"Could not identify the next token.", pos.lineno, pos.colno, buf
)
except LexException as e:
if e.source is None:
e.source = buf
raise
|
def tokenize(buf):
"""
Tokenize a Lisp file or string buffer into internal Hy objects.
"""
try:
return parser.parse(lexer.lex(buf))
except LexingError as e:
pos = e.getsourcepos()
raise LexException("Could not identify the next token.", pos.lineno, pos.colno)
except LexException as e:
if e.source is None:
e.source = buf
raise
|
https://github.com/hylang/hy/issues/1252
|
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "hy/cmdline.py", line 406, in hy2py_main
if stdin_text is None
File "hy/cmdline.py", line 186, in pretty_error
print(e, file=sys.stderr)
File "hy/lex/exceptions.py", line 43, in __str__
source = self.source.split("\n")
AttributeError: 'NoneType' object has no attribute 'split'
|
AttributeError
|
def __init__(self, message, lineno, colno, source=None):
super(LexException, self).__init__(message)
self.message = message
self.lineno = lineno
self.colno = colno
self.source = source
self.filename = "<stdin>"
|
def __init__(self, message, lineno, colno):
super(LexException, self).__init__(message)
self.message = message
self.lineno = lineno
self.colno = colno
self.source = None
self.filename = "<stdin>"
|
https://github.com/hylang/hy/issues/1252
|
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "hy/cmdline.py", line 406, in hy2py_main
if stdin_text is None
File "hy/cmdline.py", line 186, in pretty_error
print(e, file=sys.stderr)
File "hy/lex/exceptions.py", line 43, in __str__
source = self.source.split("\n")
AttributeError: 'NoneType' object has no attribute 'split'
|
AttributeError
|
def runsource(self, source, filename="<input>", symbol="single"):
global SIMPLE_TRACEBACKS
try:
tokens = tokenize(source)
except PrematureEndOfInput:
return True
except LexException as e:
if e.source is None:
e.source = source
e.filename = filename
print(e, file=sys.stderr)
return False
try:
_ast = hy_compile(tokens, "__console__", root=ast.Interactive)
if self.spy:
print_python_code(_ast)
code = ast_compile(_ast, filename, symbol)
except HyTypeError as e:
if e.source is None:
e.source = source
e.filename = filename
if SIMPLE_TRACEBACKS:
print(e, file=sys.stderr)
else:
self.showtraceback()
return False
except Exception:
self.showtraceback()
return False
self.runcode(code)
return False
|
def runsource(self, source, filename="<input>", symbol="single"):
global SIMPLE_TRACEBACKS
try:
tokens = tokenize(source)
except PrematureEndOfInput:
return True
except LexException as e:
if e.source is None:
e.source = source
e.filename = filename
sys.stderr.write(str(e))
return False
try:
_ast = hy_compile(tokens, "__console__", root=ast.Interactive)
if self.spy:
print_python_code(_ast)
code = ast_compile(_ast, filename, symbol)
except HyTypeError as e:
if e.source is None:
e.source = source
e.filename = filename
if SIMPLE_TRACEBACKS:
sys.stderr.write(str(e))
else:
self.showtraceback()
return False
except Exception:
self.showtraceback()
return False
self.runcode(code)
return False
|
https://github.com/hylang/hy/issues/982
|
Traceback (most recent call last):
File "/usr/bin/hy", line 9, in <module>
load_entry_point('hy==0.11.0', 'console_scripts', 'hy')()
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 347, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 342, in cmdline_handler
return run_repl(spy=options.spy)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 240, in run_repl
os=platform.system()
File "/usr/lib64/python2.7/code.py", line 243, in interact
more = self.push(line)
File "/usr/lib64/python2.7/code.py", line 265, in push
more = self.runsource(source, self.filename)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 113, in runsource
sys.stderr.write(str(e))
File "/usr/lib/python2.7/site-packages/hy/errors.py", line 104, in __str__
self.message))
File "/usr/lib/python2.7/site-packages/clint/textui/colored.py", line 108, in __radd__
return str(other) + str(self.color_str)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufdd0' in position 24: ordinal not in range(128)
|
UnicodeEncodeError
|
def pretty_error(func, *args, **kw):
try:
return func(*args, **kw)
except (HyTypeError, LexException) as e:
if SIMPLE_TRACEBACKS:
print(e, file=sys.stderr)
sys.exit(1)
raise
|
def pretty_error(func, *args, **kw):
try:
return func(*args, **kw)
except (HyTypeError, LexException) as e:
if SIMPLE_TRACEBACKS:
sys.stderr.write(str(e))
sys.exit(1)
raise
|
https://github.com/hylang/hy/issues/982
|
Traceback (most recent call last):
File "/usr/bin/hy", line 9, in <module>
load_entry_point('hy==0.11.0', 'console_scripts', 'hy')()
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 347, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 342, in cmdline_handler
return run_repl(spy=options.spy)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 240, in run_repl
os=platform.system()
File "/usr/lib64/python2.7/code.py", line 243, in interact
more = self.push(line)
File "/usr/lib64/python2.7/code.py", line 265, in push
more = self.runsource(source, self.filename)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 113, in runsource
sys.stderr.write(str(e))
File "/usr/lib/python2.7/site-packages/hy/errors.py", line 104, in __str__
self.message))
File "/usr/lib/python2.7/site-packages/clint/textui/colored.py", line 108, in __radd__
return str(other) + str(self.color_str)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufdd0' in position 24: ordinal not in range(128)
|
UnicodeEncodeError
|
def run_module(mod_name):
from hy.importer import MetaImporter
pth = MetaImporter().find_on_path(mod_name)
if pth is not None:
sys.argv = [pth] + sys.argv
return run_file(pth)
print(
"{0}: module '{1}' not found.\n".format(hy.__appname__, mod_name),
file=sys.stderr,
)
return 1
|
def run_module(mod_name):
from hy.importer import MetaImporter
pth = MetaImporter().find_on_path(mod_name)
if pth is not None:
sys.argv = [pth] + sys.argv
return run_file(pth)
sys.stderr.write("{0}: module '{1}' not found.\n".format(hy.__appname__, mod_name))
return 1
|
https://github.com/hylang/hy/issues/982
|
Traceback (most recent call last):
File "/usr/bin/hy", line 9, in <module>
load_entry_point('hy==0.11.0', 'console_scripts', 'hy')()
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 347, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 342, in cmdline_handler
return run_repl(spy=options.spy)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 240, in run_repl
os=platform.system()
File "/usr/lib64/python2.7/code.py", line 243, in interact
more = self.push(line)
File "/usr/lib64/python2.7/code.py", line 265, in push
more = self.runsource(source, self.filename)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 113, in runsource
sys.stderr.write(str(e))
File "/usr/lib/python2.7/site-packages/hy/errors.py", line 104, in __str__
self.message))
File "/usr/lib/python2.7/site-packages/clint/textui/colored.py", line 108, in __radd__
return str(other) + str(self.color_str)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufdd0' in position 24: ordinal not in range(128)
|
UnicodeEncodeError
|
def cmdline_handler(scriptname, argv):
parser = argparse.ArgumentParser(
prog="hy",
usage=USAGE,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=EPILOG,
)
parser.add_argument("-c", dest="command", help="program passed in as a string")
parser.add_argument("-m", dest="mod", help="module to run, passed in as a string")
parser.add_argument(
"-i", dest="icommand", help="program passed in as a string, then stay in REPL"
)
parser.add_argument(
"--spy",
action="store_true",
help="print equivalent Python code before executing",
)
parser.add_argument("-v", action="version", version=VERSION)
parser.add_argument(
"--show-tracebacks",
action="store_true",
help="show complete tracebacks for Hy exceptions",
)
# this will contain the script/program name and any arguments for it.
parser.add_argument("args", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
# stash the hy executable in case we need it later
# mimics Python sys.executable
hy.executable = argv[0]
# need to split the args if using "-m"
# all args after the MOD are sent to the module
# in sys.argv
module_args = []
if "-m" in argv:
mloc = argv.index("-m")
if len(argv) > mloc + 2:
module_args = argv[mloc + 2 :]
argv = argv[: mloc + 2]
options = parser.parse_args(argv[1:])
if options.show_tracebacks:
global SIMPLE_TRACEBACKS
SIMPLE_TRACEBACKS = False
# reset sys.argv like Python
sys.argv = options.args + module_args or [""]
if options.command:
# User did "hy -c ..."
return run_command(options.command)
if options.mod:
# User did "hy -m ..."
return run_module(options.mod)
if options.icommand:
# User did "hy -i ..."
return run_icommand(options.icommand, spy=options.spy)
if options.args:
if options.args[0] == "-":
# Read the program from stdin
return run_command(sys.stdin.read())
else:
# User did "hy <filename>"
try:
return run_file(options.args[0])
except HyIOError as e:
print(
"hy: Can't open file '{0}': [Errno {1}] {2}\n".format(
e.filename, e.errno, e.strerror
),
file=sys.stderr,
)
sys.exit(e.errno)
# User did NOTHING!
return run_repl(spy=options.spy)
|
def cmdline_handler(scriptname, argv):
parser = argparse.ArgumentParser(
prog="hy",
usage=USAGE,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=EPILOG,
)
parser.add_argument("-c", dest="command", help="program passed in as a string")
parser.add_argument("-m", dest="mod", help="module to run, passed in as a string")
parser.add_argument(
"-i", dest="icommand", help="program passed in as a string, then stay in REPL"
)
parser.add_argument(
"--spy",
action="store_true",
help="print equivalent Python code before executing",
)
parser.add_argument("-v", action="version", version=VERSION)
parser.add_argument(
"--show-tracebacks",
action="store_true",
help="show complete tracebacks for Hy exceptions",
)
# this will contain the script/program name and any arguments for it.
parser.add_argument("args", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
# stash the hy executable in case we need it later
# mimics Python sys.executable
hy.executable = argv[0]
# need to split the args if using "-m"
# all args after the MOD are sent to the module
# in sys.argv
module_args = []
if "-m" in argv:
mloc = argv.index("-m")
if len(argv) > mloc + 2:
module_args = argv[mloc + 2 :]
argv = argv[: mloc + 2]
options = parser.parse_args(argv[1:])
if options.show_tracebacks:
global SIMPLE_TRACEBACKS
SIMPLE_TRACEBACKS = False
# reset sys.argv like Python
sys.argv = options.args + module_args or [""]
if options.command:
# User did "hy -c ..."
return run_command(options.command)
if options.mod:
# User did "hy -m ..."
return run_module(options.mod)
if options.icommand:
# User did "hy -i ..."
return run_icommand(options.icommand, spy=options.spy)
if options.args:
if options.args[0] == "-":
# Read the program from stdin
return run_command(sys.stdin.read())
else:
# User did "hy <filename>"
try:
return run_file(options.args[0])
except HyIOError as e:
sys.stderr.write(
"hy: Can't open file '%s': [Errno %d] %s\n"
% (e.filename, e.errno, e.strerror)
)
sys.exit(e.errno)
# User did NOTHING!
return run_repl(spy=options.spy)
|
https://github.com/hylang/hy/issues/982
|
Traceback (most recent call last):
File "/usr/bin/hy", line 9, in <module>
load_entry_point('hy==0.11.0', 'console_scripts', 'hy')()
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 347, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 342, in cmdline_handler
return run_repl(spy=options.spy)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 240, in run_repl
os=platform.system()
File "/usr/lib64/python2.7/code.py", line 243, in interact
more = self.push(line)
File "/usr/lib64/python2.7/code.py", line 265, in push
more = self.runsource(source, self.filename)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 113, in runsource
sys.stderr.write(str(e))
File "/usr/lib/python2.7/site-packages/hy/errors.py", line 104, in __str__
self.message))
File "/usr/lib/python2.7/site-packages/clint/textui/colored.py", line 108, in __radd__
return str(other) + str(self.color_str)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufdd0' in position 24: ordinal not in range(128)
|
UnicodeEncodeError
|
def hyc_main():
from hy.importer import write_hy_as_pyc
parser = argparse.ArgumentParser(prog="hyc")
parser.add_argument("files", metavar="FILE", nargs="+", help="file to compile")
parser.add_argument("-v", action="version", version=VERSION)
options = parser.parse_args(sys.argv[1:])
for file in options.files:
try:
print("Compiling %s" % file)
pretty_error(write_hy_as_pyc, file)
except IOError as x:
print(
"hyc: Can't open file '{0}': [Errno {1}] {2}\n".format(
x.filename, x.errno, x.strerror
),
file=sys.stderr,
)
sys.exit(x.errno)
|
def hyc_main():
from hy.importer import write_hy_as_pyc
parser = argparse.ArgumentParser(prog="hyc")
parser.add_argument("files", metavar="FILE", nargs="+", help="file to compile")
parser.add_argument("-v", action="version", version=VERSION)
options = parser.parse_args(sys.argv[1:])
for file in options.files:
try:
print("Compiling %s" % file)
pretty_error(write_hy_as_pyc, file)
except IOError as x:
sys.stderr.write(
"hyc: Can't open file '%s': [Errno %d] %s\n"
% (x.filename, x.errno, x.strerror)
)
sys.exit(x.errno)
|
https://github.com/hylang/hy/issues/982
|
Traceback (most recent call last):
File "/usr/bin/hy", line 9, in <module>
load_entry_point('hy==0.11.0', 'console_scripts', 'hy')()
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 347, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 342, in cmdline_handler
return run_repl(spy=options.spy)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 240, in run_repl
os=platform.system()
File "/usr/lib64/python2.7/code.py", line 243, in interact
more = self.push(line)
File "/usr/lib64/python2.7/code.py", line 265, in push
more = self.runsource(source, self.filename)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 113, in runsource
sys.stderr.write(str(e))
File "/usr/lib/python2.7/site-packages/hy/errors.py", line 104, in __str__
self.message))
File "/usr/lib/python2.7/site-packages/clint/textui/colored.py", line 108, in __radd__
return str(other) + str(self.color_str)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufdd0' in position 24: ordinal not in range(128)
|
UnicodeEncodeError
|
def __str__(self):
line = self.expression.start_line
start = self.expression.start_column
end = self.expression.end_column
source = []
if self.source is not None:
source = self.source.split("\n")[line - 1 : self.expression.end_line]
if line == self.expression.end_line:
length = end - start
else:
length = len(source[0]) - start
result = ""
result += ' File "%s", line %d, column %d\n\n' % (self.filename, line, start)
if len(source) == 1:
result += " %s\n" % colored.red(source[0])
result += " %s%s\n" % (
" " * (start - 1),
colored.green("^" + "-" * (length - 1) + "^"),
)
if len(source) > 1:
result += " %s\n" % colored.red(source[0])
result += " %s%s\n" % (" " * (start - 1), colored.green("^" + "-" * length))
if len(source) > 2: # write the middle lines
for line in source[1:-1]:
result += " %s\n" % colored.red("".join(line))
result += " %s\n" % colored.green("-" * len(line))
# write the last line
result += " %s\n" % colored.red("".join(source[-1]))
result += " %s\n" % colored.green("-" * (end - 1) + "^")
result += colored.yellow(
"%s: %s\n\n" % (self.__class__.__name__, self.message.encode("utf-8"))
)
return result
|
def __str__(self):
line = self.expression.start_line
start = self.expression.start_column
end = self.expression.end_column
source = []
if self.source is not None:
source = self.source.split("\n")[line - 1 : self.expression.end_line]
if line == self.expression.end_line:
length = end - start
else:
length = len(source[0]) - start
result = ""
result += ' File "%s", line %d, column %d\n\n' % (self.filename, line, start)
if len(source) == 1:
result += " %s\n" % colored.red(source[0])
result += " %s%s\n" % (
" " * (start - 1),
colored.green("^" + "-" * (length - 1) + "^"),
)
if len(source) > 1:
result += " %s\n" % colored.red(source[0])
result += " %s%s\n" % (" " * (start - 1), colored.green("^" + "-" * length))
if len(source) > 2: # write the middle lines
for line in source[1:-1]:
result += " %s\n" % colored.red("".join(line))
result += " %s\n" % colored.green("-" * len(line))
# write the last line
result += " %s\n" % colored.red("".join(source[-1]))
result += " %s\n" % colored.green("-" * (end - 1) + "^")
result += colored.yellow("%s: %s\n\n" % (self.__class__.__name__, self.message))
if not PY3:
return result.encode("utf-8")
else:
return result
|
https://github.com/hylang/hy/issues/982
|
Traceback (most recent call last):
File "/usr/bin/hy", line 9, in <module>
load_entry_point('hy==0.11.0', 'console_scripts', 'hy')()
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 347, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 342, in cmdline_handler
return run_repl(spy=options.spy)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 240, in run_repl
os=platform.system()
File "/usr/lib64/python2.7/code.py", line 243, in interact
more = self.push(line)
File "/usr/lib64/python2.7/code.py", line 265, in push
more = self.runsource(source, self.filename)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 113, in runsource
sys.stderr.write(str(e))
File "/usr/lib/python2.7/site-packages/hy/errors.py", line 104, in __str__
self.message))
File "/usr/lib/python2.7/site-packages/clint/textui/colored.py", line 108, in __radd__
return str(other) + str(self.color_str)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufdd0' in position 24: ordinal not in range(128)
|
UnicodeEncodeError
|
def _compile_assign(self, name, result, start_line, start_column):
str_name = "%s" % name
if _is_hy_builtin(str_name, self.module_name):
raise HyTypeError(name, "Can't assign to a builtin: `%s'" % str_name)
result = self.compile(result)
ld_name = self.compile(name)
if isinstance(ld_name.expr, ast.Call):
raise HyTypeError(name, "Can't assign to a callable: `%s'" % str_name)
if result.temp_variables and isinstance(name, HyString) and "." not in name:
result.rename(name)
else:
st_name = self._storeize(ld_name)
result += ast.Assign(
lineno=start_line,
col_offset=start_column,
targets=[st_name],
value=result.force_expr,
)
result += ld_name
return result
|
def _compile_assign(self, name, result, start_line, start_column):
str_name = "%s" % name
if _is_hy_builtin(str_name, self.module_name):
raise HyTypeError(name, "Can't assign to a builtin: `%s'" % str_name)
result = self.compile(result)
ld_name = self.compile(name)
if result.temp_variables and isinstance(name, HyString) and "." not in name:
result.rename(name)
else:
st_name = self._storeize(ld_name)
result += ast.Assign(
lineno=start_line,
col_offset=start_column,
targets=[st_name],
value=result.force_expr,
)
result += ld_name
return result
|
https://github.com/hylang/hy/issues/532
|
=> (let [x 4] x)
Traceback (most recent call last):
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 2150, in hy_compile
result = compiler.compile(tree)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 398, in compile
ret = self.compile_atom(_type, tree)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 390, in compile_atom
ret = _compile_table[atom_type](self, atom)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 544, in compile_raw_list
ret = self._compile_branch(entries)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 429, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 290, in _branch
results = list(results)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 429, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 398, in compile
ret = self.compile_atom(_type, tree)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 390, in compile_atom
ret = _compile_table[atom_type](self, atom)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 1712, in compile_expression
func = self.compile(fn)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 398, in compile
ret = self.compile_atom(_type, tree)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 390, in compile_atom
ret = _compile_table[atom_type](self, atom)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 1686, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 390, in compile_atom
ret = _compile_table[atom_type](self, atom)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 333, in checker
return fn(self, expression)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 1871, in compile_function_def
body = self._compile_branch(expression)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 429, in _compile_branch
return _branch(self.compile(expr) for expr in exprs)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 290, in _branch
results = list(results)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 429, in <genexpr>
return _branch(self.compile(expr) for expr in exprs)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 410, in compile
raise HyCompileError(e, sys.exc_info()[2])
HyCompileError: Internal Compiler Bug
⤷ TypeError: Can't assign / delete a <class '_ast.Num'> object
Compilation traceback:
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 398, in compile
ret = self.compile_atom(_type, tree)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 390, in compile_atom
ret = _compile_table[atom_type](self, atom)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 1686, in compile_expression
ret = self.compile_atom(fn, expression)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 390, in compile_atom
ret = _compile_table[atom_type](self, atom)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 333, in checker
return fn(self, expression)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 1731, in compile_def_expression
expression.start_column)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 1742, in _compile_assign
st_name = self._storeize(ld_name)
File "/home/at/.local/lib/python2.7/site-packages/hy/compiler.py", line 536, in _storeize
raise TypeError("Can't assign / delete a %s object" % type(name))
|
HyCompileError
|
def compile_list_comprehension(self, expr):
# (list-comp expr (target iter) cond?)
expr.pop(0)
expression = expr.pop(0)
gen_gen = expr[0]
if not isinstance(gen_gen, HyList):
raise HyTypeError(gen_gen, "Generator expression must be a list.")
gen_res, gen = self._compile_generator_iterables(expr)
if len(gen) == 0:
raise HyTypeError(gen_gen, "Generator expression cannot be empty.")
compiled_expression = self.compile(expression)
ret = compiled_expression + gen_res
ret += ast.ListComp(
lineno=expr.start_line,
col_offset=expr.start_column,
elt=compiled_expression.force_expr,
generators=gen,
)
return ret
|
def compile_list_comprehension(self, expr):
# (list-comp expr (target iter) cond?)
expr.pop(0)
expression = expr.pop(0)
gen_res, gen = self._compile_generator_iterables(expr)
compiled_expression = self.compile(expression)
ret = compiled_expression + gen_res
ret += ast.ListComp(
lineno=expr.start_line,
col_offset=expr.start_column,
elt=compiled_expression.force_expr,
generators=gen,
)
return ret
|
https://github.com/hylang/hy/issues/634
|
ryan@DevPC-LX:~/stuff/hy$ ~/stuff/anaconda/bin/hy
hy 0.10.0 using CPython(default) 3.3.5 on Linux
=> (list-comp [x [1 2 3]] x)
Traceback (most recent call last):
File "/home/ryan/stuff/anaconda/lib/python3.3/site-packages/hy-0.10.0-py3.3.egg/hy/importer.py", line 42, in ast_compile
return compile(ast, filename, mode, flags)
ValueError: comprehension with no generators
=>
|
ValueError
|
def __repr__(self):
return f"piid: {self.iid} ({self.description}): ({self.format}, unit: {self.unit}) (acc: {self.access})"
|
def __repr__(self):
return f"piid: {self.iid} ({self.description}): ({self.format}, unit: {self.unit}) (acc: {self.access}, value-list: {self.value_list}, value-range: {self.value_range})"
|
https://github.com/rytilahti/python-miio/issues/885
|
Traceback (most recent call last):
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/dataclasses_json/core.py", line 263, in _decode_generic
res = _get_type_cons(type_)(xs)
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/dataclasses_json/core.py", line 306, in <genexpr>
items = (_decode_dataclass(type_arg, x, infer_missing)
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/dataclasses_json/core.py", line 201, in _decode_dataclass
init_kwargs[field.name] = _decode_generic(field_type,
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/dataclasses_json/core.py", line 258, in _decode_generic
xs = _decode_items(type_.__args__[0], value, infer_missing)
File "/usr/local/Cellar/python@3.9/3.9.0_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/typing.py", line 648, in __getattr__
raise AttributeError(attr)
AttributeError: __args__
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/dataclasses_json/core.py", line 263, in _decode_generic
res = _get_type_cons(type_)(xs)
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/dataclasses_json/core.py", line 306, in <genexpr>
items = (_decode_dataclass(type_arg, x, infer_missing)
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/dataclasses_json/core.py", line 201, in _decode_dataclass
init_kwargs[field.name] = _decode_generic(field_type,
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/dataclasses_json/core.py", line 265, in _decode_generic
res = type_(xs)
File "/usr/local/Cellar/python@3.9/3.9.0_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/typing.py", line 622, in __call__
raise TypeError(f"Type {self._name} cannot be instantiated; "
TypeError: Type List cannot be instantiated; use list() instead
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/ihor_syerkov/source/temp/python-miio/devtools/miottemplate.py", line 65, in <module>
cli()
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/ihor_syerkov/source/temp/python-miio/devtools/miottemplate.py", line 47, in generate
print(gen.generate())
File "/Users/ihor_syerkov/source/temp/python-miio/devtools/miottemplate.py", line 25, in generate
dev = Device.from_json(self.data)
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/dataclasses_json/api.py", line 76, in from_json
return cls.from_dict(kvs, infer_missing=infer_missing)
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/dataclasses_json/api.py", line 83, in from_dict
return _decode_dataclass(cls, kvs, infer_missing)
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/dataclasses_json/core.py", line 201, in _decode_dataclass
init_kwargs[field.name] = _decode_generic(field_type,
File "/Users/ihor_syerkov/Library/Caches/pypoetry/virtualenvs/python-miio-HruUc-gR-py3.9/lib/python3.9/site-packages/dataclasses_json/core.py", line 265, in _decode_generic
res = type_(xs)
File "/usr/local/Cellar/python@3.9/3.9.0_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/typing.py", line 622, in __call__
raise TypeError(f"Type {self._name} cannot be instantiated; "
TypeError: Type List cannot be instantiated; use list() instead```
|
AttributeError
|
def other_package_info(info, desc):
"""Return information about another package supporting the device."""
return "Found %s at %s, check %s" % (info.name, get_addr_from_info(info), desc)
|
def other_package_info(info, desc):
"""Return information about another package supporting the device."""
return "%s @ %s, check %s" % (info.name, ipaddress.ip_address(info.address), desc)
|
https://github.com/rytilahti/python-miio/issues/891
|
INFO:miio.discovery:Discovering devices with mDNS, press any key to quit...
Exception in thread zeroconf-ServiceBrowser__miio._udp.local._229705:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
self.run()
File "/home/user/.local/lib/python3.9/site-packages/zeroconf/__init__.py", line 1750, in run
self._service_state_changed.fire(
File "/home/user/.local/lib/python3.9/site-packages/zeroconf/__init__.py", line 1508, in fire
h(**kwargs)
File "/home/user/.local/lib/python3.9/site-packages/zeroconf/__init__.py", line 1606, in on_change
listener.add_service(*args)
File "/home/user/.local/lib/python3.9/site-packages/miio/discovery.py", line 256, in add_service
addr = str(ipaddress.ip_address(info.address))
AttributeError: 'ServiceInfo' object has no attribute 'address'
|
AttributeError
|
def add_service(self, zeroconf, type, name):
info = zeroconf.get_service_info(type, name)
addr = get_addr_from_info(info)
if addr not in self.found_devices:
dev = self.check_and_create_device(info, addr)
self.found_devices[addr] = dev
|
def add_service(self, zeroconf, type, name):
info = zeroconf.get_service_info(type, name)
addr = str(ipaddress.ip_address(info.address))
if addr not in self.found_devices:
dev = self.check_and_create_device(info, addr)
self.found_devices[addr] = dev
|
https://github.com/rytilahti/python-miio/issues/891
|
INFO:miio.discovery:Discovering devices with mDNS, press any key to quit...
Exception in thread zeroconf-ServiceBrowser__miio._udp.local._229705:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
self.run()
File "/home/user/.local/lib/python3.9/site-packages/zeroconf/__init__.py", line 1750, in run
self._service_state_changed.fire(
File "/home/user/.local/lib/python3.9/site-packages/zeroconf/__init__.py", line 1508, in fire
h(**kwargs)
File "/home/user/.local/lib/python3.9/site-packages/zeroconf/__init__.py", line 1606, in on_change
listener.add_service(*args)
File "/home/user/.local/lib/python3.9/site-packages/miio/discovery.py", line 256, in add_service
addr = str(ipaddress.ip_address(info.address))
AttributeError: 'ServiceInfo' object has no attribute 'address'
|
AttributeError
|
def timezone(self):
"""Get the timezone."""
res = self.send("get_timezone")[0]
if isinstance(res, dict):
# Xiaowa E25 example
# {'olson': 'Europe/Berlin', 'posix': 'CET-1CEST,M3.5.0,M10.5.0/3'}
if "olson" not in res:
raise VacuumException("Unsupported timezone format: %s" % res)
return res["olson"]
# Gen1 vacuum: ['Europe/Berlin']
return res
|
def timezone(self):
"""Get the timezone."""
return self.send("get_timezone")[0]
|
https://github.com/rytilahti/python-miio/issues/759
|
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 186, in _async_setup_platform
await asyncio.gather(*pending)
File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 292, in async_add_entities
await asyncio.gather(*tasks)
File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 451, in _async_add_entity
entity.async_write_ha_state()
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 290, in async_write_ha_state
self._async_write_ha_state()
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 317, in _async_write_ha_state
attr.update(self.device_state_attributes or {})
File "/usr/src/homeassistant/homeassistant/components/xiaomi_miio/vacuum.py", line 333, in device_state_attributes
if self.timers:
File "/usr/src/homeassistant/homeassistant/components/xiaomi_miio/vacuum.py", line 284, in timers
for timer in self._timers
File "/usr/src/homeassistant/homeassistant/components/xiaomi_miio/vacuum.py", line 284, in <listcomp>
for timer in self._timers
File "/usr/local/lib/python3.7/site-packages/miio/vacuumcontainers.py", line 444, in next_schedule
local_tz = timezone(self.timezone)
File "/usr/local/lib/python3.7/site-packages/pytz/__init__.py", line 163, in timezone
if zone.upper() == 'UTC':
AttributeError: 'dict' object has no attribute 'upper'
|
AttributeError
|
def last_clean_details(self) -> Optional[CleaningDetails]:
"""Return details from the last cleaning.
Returns None if there has been no cleanups."""
history = self.clean_history()
if not history.ids:
return None
last_clean_id = history.ids.pop(0)
return self.clean_details(last_clean_id, return_list=False)
|
def last_clean_details(self) -> CleaningDetails:
"""Return details from the last cleaning."""
last_clean_id = self.clean_history().ids.pop(0)
return self.clean_details(last_clean_id, return_list=False)
|
https://github.com/rytilahti/python-miio/issues/457
|
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity_platform.py", line 248, in _async_add_entity
await entity.async_device_update(warning=False)
File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 349, in async_device_update
await self.hass.async_add_executor_job(self.update)
File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/local/lib/python3.6/site-packages/homeassistant/components/vacuum/xiaomi_miio.py", line 378, in update
self.last_clean = self._vacuum.last_clean_details()
File "/usr/local/lib/python3.6/site-packages/miio/vacuum.py", line 194, in last_clean_details
last_clean_id = self.clean_history().ids.pop(0)
IndexError: pop from empty list
|
IndexError
|
def info(vac: miio.Vacuum):
"""Return device information."""
try:
res = vac.info()
click.echo("%s" % res)
_LOGGER.debug("Full response: %s", pf(res.raw))
except TypeError:
click.echo(
"Unable to fetch info, this can happen when the vacuum "
"is not connected to the Xiaomi cloud."
)
|
def info(vac: miio.Vacuum):
"""Return device information."""
res = vac.info()
click.echo("%s" % res)
_LOGGER.debug("Full response: %s", pf(res.raw))
|
https://github.com/rytilahti/python-miio/issues/156
|
INFO:miio.vacuum_cli:Debug mode active
DEBUG:miio.vacuum_cli:Read stored sequence ids: {'seq': 645, 'manual_seq': 0}
DEBUG:miio.vacuum_cli:Connecting to 10.0.11.100 with token xxxxxxxxxxxxx
DEBUG:miio.protocol:Unable to decrypt, returning raw bytes: b''
DEBUG:miio.device:Got a response: Container:
data = Container:
data = (total 0)
value = (total 0)
offset1 = 32
offset2 = 32
length = 0
header = Container:
data = !1\x00 \x00\x00\x00\x00\x04m\xf8\xe2\x00\x00\x1e\xf1 (total 16)
value = Container:
length = 32
unknown = 0
device_id = 00aabbcc (total 8)
ts = 1970-01-01 02:12:01
offset1 = 0
offset2 = 16
length = 16
checksum = \xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff (total 16)
DEBUG:miio.device:Discovered b'00aabbcc' with ts: 1970-01-01 02:12:01, token: b'ffffffffffffffffffffffffffffffff'
DEBUG:miio.device:10.0.11.100:54321 >>: {'id': 646, 'method': 'miIO.info', 'params': []}
ERROR:miio.protocol:unable to parse json '': Expecting value: line 1 column 1 (char 0)
Traceback (most recent call last):
File "/usr/bin/mirobo", line 11, in <module>
load_entry_point('python-miio==0.3.3', 'console_scripts', 'mirobo')()
File "/usr/lib/python3/dist-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/usr/lib/python3/dist-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/usr/lib/python3/dist-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/lib/python3/dist-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/lib/python3/dist-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/usr/lib/python3/dist-packages/click/decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args[1:], **kwargs)
File "/usr/lib/python3/dist-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/usr/lib/python3/dist-packages/miio/vacuum_cli.py", line 391, in info
res = vac.info()
File "/usr/lib/python3/dist-packages/miio/device.py", line 271, in info
return DeviceInfo(self.send("miIO.info", []))
File "/usr/lib/python3/dist-packages/miio/device.py", line 239, in send
self.__id = m.data.value["id"]
TypeError: 'NoneType' object is not subscriptable
|
TypeError
|
def batching(
func: Callable[[Any], np.ndarray] = None,
batch_size: Union[int, Callable] = None,
num_batch: Optional[int] = None,
split_over_axis: int = 0,
merge_over_axis: int = 0,
slice_on: int = 1,
label_on: Optional[int] = None,
ordinal_idx_arg: Optional[int] = None,
) -> Any:
"""Split the input of a function into small batches and call :func:`func` on each batch
, collect the merged result and return. This is useful when the input is too big to fit into memory
:param func: function to decorate
:param batch_size: size of each batch
:param num_batch: number of batches to take, the rest will be ignored
:param split_over_axis: split over which axis into batches
:param merge_over_axis: merge over which axis into a single result
:param slice_on: the location of the data. When using inside a class,
``slice_on`` should take ``self`` into consideration.
:param label_on: the location of the labels. Useful for data with any kind of accompanying labels
:param ordinal_idx_arg: the location of the ordinal indexes argument. Needed for classes
where function decorated needs to know the ordinal indexes of the data in the batch
(Not used when label_on is used)
:return: the merged result as if run :func:`func` once on the input.
Example:
.. highlight:: python
.. code-block:: python
class MemoryHungryExecutor:
@batching
def train(self, batch: 'numpy.ndarray', *args, **kwargs):
gpu_train(batch) #: this will respect the ``batch_size`` defined as object attribute
@batching(batch_size = 64)
def train(self, batch: 'numpy.ndarray', *args, **kwargs):
gpu_train(batch)
"""
def _batching(func):
@wraps(func)
def arg_wrapper(*args, **kwargs):
# priority: decorator > class_attribute
# by default data is in args[1] (self needs to be taken into account)
data = args[slice_on]
args = list(args)
b_size = (
batch_size(data) if callable(batch_size) else batch_size
) or getattr(args[0], "batch_size", None)
# no batching if b_size is None
if b_size is None or data is None:
return func(*args, **kwargs)
default_logger.debug(
f"batching enabled for {func.__qualname__} batch_size={b_size} "
f"num_batch={num_batch} axis={split_over_axis}"
)
full_data_size = _get_size(data, split_over_axis)
total_size = _get_total_size(full_data_size, batch_size, num_batch)
final_result = []
data = (data, args[label_on]) if label_on else data
yield_slice = isinstance(data, np.memmap)
slice_idx = None
for b in batch_iterator(
data[:total_size], b_size, split_over_axis, yield_slice=yield_slice
):
if yield_slice:
slice_idx = b
new_memmap = np.memmap(
data.filename, dtype=data.dtype, mode="r", shape=data.shape
)
b = new_memmap[slice_idx]
slice_idx = slice_idx[split_over_axis]
if slice_idx.start is None or slice_idx.stop is None:
slice_idx = None
if not isinstance(b, tuple):
# for now, keeping ordered_idx is only supported if no labels
args[slice_on] = b
if ordinal_idx_arg and slice_idx is not None:
args[ordinal_idx_arg] = slice_idx
else:
args[slice_on] = b[0]
args[label_on] = b[1]
r = func(*args, **kwargs)
if yield_slice:
del new_memmap
if r is not None:
final_result.append(r)
return _merge_results_after_batching(final_result, merge_over_axis)
return arg_wrapper
if func:
return _batching(func)
else:
return _batching
|
def batching(
func: Callable[[Any], np.ndarray] = None,
batch_size: Union[int, Callable] = None,
num_batch: Optional[int] = None,
split_over_axis: int = 0,
merge_over_axis: int = 0,
slice_on: int = 1,
label_on: Optional[int] = None,
ordinal_idx_arg: Optional[int] = None,
) -> Any:
"""Split the input of a function into small batches and call :func:`func` on each batch
, collect the merged result and return. This is useful when the input is too big to fit into memory
:param func: function to decorate
:param batch_size: size of each batch
:param num_batch: number of batches to take, the rest will be ignored
:param split_over_axis: split over which axis into batches
:param merge_over_axis: merge over which axis into a single result
:param slice_on: the location of the data. When using inside a class,
``slice_on`` should take ``self`` into consideration.
:param label_on: the location of the labels. Useful for data with any kind of accompanying labels
:param ordinal_idx_arg: the location of the ordinal indexes argument. Needed for classes
where function decorated needs to know the ordinal indexes of the data in the batch
(Not used when label_on is used)
:return: the merged result as if run :func:`func` once on the input.
Example:
.. highlight:: python
.. code-block:: python
class MemoryHungryExecutor:
@batching
def train(self, batch: 'numpy.ndarray', *args, **kwargs):
gpu_train(batch) #: this will respect the ``batch_size`` defined as object attribute
@batching(batch_size = 64)
def train(self, batch: 'numpy.ndarray', *args, **kwargs):
gpu_train(batch)
"""
def _batching(func):
@wraps(func)
def arg_wrapper(*args, **kwargs):
# priority: decorator > class_attribute
# by default data is in args[1] (self needs to be taken into account)
data = args[slice_on]
args = list(args)
b_size = (
batch_size(data) if callable(batch_size) else batch_size
) or getattr(args[0], "batch_size", None)
# no batching if b_size is None
if b_size is None:
return func(*args, **kwargs)
default_logger.debug(
f"batching enabled for {func.__qualname__} batch_size={b_size} "
f"num_batch={num_batch} axis={split_over_axis}"
)
full_data_size = _get_size(data, split_over_axis)
total_size = _get_total_size(full_data_size, batch_size, num_batch)
final_result = []
data = (data, args[label_on]) if label_on else data
yield_slice = isinstance(data, np.memmap)
slice_idx = None
for b in batch_iterator(
data[:total_size], b_size, split_over_axis, yield_slice=yield_slice
):
if yield_slice:
slice_idx = b
new_memmap = np.memmap(
data.filename, dtype=data.dtype, mode="r", shape=data.shape
)
b = new_memmap[slice_idx]
slice_idx = slice_idx[split_over_axis]
if slice_idx.start is None or slice_idx.stop is None:
slice_idx = None
if not isinstance(b, tuple):
# for now, keeping ordered_idx is only supported if no labels
args[slice_on] = b
if ordinal_idx_arg and slice_idx is not None:
args[ordinal_idx_arg] = slice_idx
else:
args[slice_on] = b[0]
args[label_on] = b[1]
r = func(*args, **kwargs)
if yield_slice:
del new_memmap
if r is not None:
final_result.append(r)
return _merge_results_after_batching(final_result, merge_over_axis)
return arg_wrapper
if func:
return _batching(func)
else:
return _batching
|
https://github.com/jina-ai/jina/issues/1229
|
Traceback (most recent call last):
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 292, in msg_callback
self.zmqlet.send_message(self._callback(msg))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 266, in _callback
self.pre_hook(msg).handle(msg).post_hook(msg)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 160, in handle
self.executor(self.request_type)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/__init__.py", line 570, in __call__
d()
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 251, in __call__
self._traverse_apply(self.req.docs, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 268, in _traverse_apply
**kwargs,
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 281, in _traverse_rec
doc.chunks, doc, 'chunks', path[1:], *args, **kwargs
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 284, in _traverse_rec
self._apply_all(docs, parent_doc, parent_edge_type, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/search.py", line 124, in _apply_all
idx, dist = self.exec_fn(embed_vecs, top_k=int(self.top_k))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/indexers/vector.py", line 279, in query
dist = self._euclidean(_keys, self.query_handler)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/decorators.py", line 241, in arg_wrapper
for b in batch_iterator(data[:total_size], b_size, split_over_axis, yield_slice=yield_slice):
TypeError: 'NoneType' object is not subscriptable
|
TypeError
|
def _batching(func):
@wraps(func)
def arg_wrapper(*args, **kwargs):
# priority: decorator > class_attribute
# by default data is in args[1] (self needs to be taken into account)
data = args[slice_on]
args = list(args)
b_size = (batch_size(data) if callable(batch_size) else batch_size) or getattr(
args[0], "batch_size", None
)
# no batching if b_size is None
if b_size is None or data is None:
return func(*args, **kwargs)
default_logger.debug(
f"batching enabled for {func.__qualname__} batch_size={b_size} "
f"num_batch={num_batch} axis={split_over_axis}"
)
full_data_size = _get_size(data, split_over_axis)
total_size = _get_total_size(full_data_size, batch_size, num_batch)
final_result = []
data = (data, args[label_on]) if label_on else data
yield_slice = isinstance(data, np.memmap)
slice_idx = None
for b in batch_iterator(
data[:total_size], b_size, split_over_axis, yield_slice=yield_slice
):
if yield_slice:
slice_idx = b
new_memmap = np.memmap(
data.filename, dtype=data.dtype, mode="r", shape=data.shape
)
b = new_memmap[slice_idx]
slice_idx = slice_idx[split_over_axis]
if slice_idx.start is None or slice_idx.stop is None:
slice_idx = None
if not isinstance(b, tuple):
# for now, keeping ordered_idx is only supported if no labels
args[slice_on] = b
if ordinal_idx_arg and slice_idx is not None:
args[ordinal_idx_arg] = slice_idx
else:
args[slice_on] = b[0]
args[label_on] = b[1]
r = func(*args, **kwargs)
if yield_slice:
del new_memmap
if r is not None:
final_result.append(r)
return _merge_results_after_batching(final_result, merge_over_axis)
return arg_wrapper
|
def _batching(func):
@wraps(func)
def arg_wrapper(*args, **kwargs):
# priority: decorator > class_attribute
# by default data is in args[1] (self needs to be taken into account)
data = args[slice_on]
args = list(args)
b_size = (batch_size(data) if callable(batch_size) else batch_size) or getattr(
args[0], "batch_size", None
)
# no batching if b_size is None
if b_size is None:
return func(*args, **kwargs)
default_logger.debug(
f"batching enabled for {func.__qualname__} batch_size={b_size} "
f"num_batch={num_batch} axis={split_over_axis}"
)
full_data_size = _get_size(data, split_over_axis)
total_size = _get_total_size(full_data_size, batch_size, num_batch)
final_result = []
data = (data, args[label_on]) if label_on else data
yield_slice = isinstance(data, np.memmap)
slice_idx = None
for b in batch_iterator(
data[:total_size], b_size, split_over_axis, yield_slice=yield_slice
):
if yield_slice:
slice_idx = b
new_memmap = np.memmap(
data.filename, dtype=data.dtype, mode="r", shape=data.shape
)
b = new_memmap[slice_idx]
slice_idx = slice_idx[split_over_axis]
if slice_idx.start is None or slice_idx.stop is None:
slice_idx = None
if not isinstance(b, tuple):
# for now, keeping ordered_idx is only supported if no labels
args[slice_on] = b
if ordinal_idx_arg and slice_idx is not None:
args[ordinal_idx_arg] = slice_idx
else:
args[slice_on] = b[0]
args[label_on] = b[1]
r = func(*args, **kwargs)
if yield_slice:
del new_memmap
if r is not None:
final_result.append(r)
return _merge_results_after_batching(final_result, merge_over_axis)
return arg_wrapper
|
https://github.com/jina-ai/jina/issues/1229
|
Traceback (most recent call last):
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 292, in msg_callback
self.zmqlet.send_message(self._callback(msg))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 266, in _callback
self.pre_hook(msg).handle(msg).post_hook(msg)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 160, in handle
self.executor(self.request_type)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/__init__.py", line 570, in __call__
d()
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 251, in __call__
self._traverse_apply(self.req.docs, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 268, in _traverse_apply
**kwargs,
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 281, in _traverse_rec
doc.chunks, doc, 'chunks', path[1:], *args, **kwargs
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 284, in _traverse_rec
self._apply_all(docs, parent_doc, parent_edge_type, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/search.py", line 124, in _apply_all
idx, dist = self.exec_fn(embed_vecs, top_k=int(self.top_k))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/indexers/vector.py", line 279, in query
dist = self._euclidean(_keys, self.query_handler)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/decorators.py", line 241, in arg_wrapper
for b in batch_iterator(data[:total_size], b_size, split_over_axis, yield_slice=yield_slice):
TypeError: 'NoneType' object is not subscriptable
|
TypeError
|
def arg_wrapper(*args, **kwargs):
data = args[slice_on]
# priority: decorator > class_attribute
# by default data is in args[1:] (self needs to be taken into account)
b_size = batch_size or getattr(args[0], "batch_size", None)
# no batching if b_size is None
if b_size is None or data is None:
return func(*args, **kwargs)
args = list(args)
default_logger.debug(
f"batching enabled for {func.__qualname__} batch_size={b_size} "
f"num_batch={num_batch} axis={split_over_axis}"
)
# assume all datas have the same length
full_data_size = _get_size(args[slice_on], split_over_axis)
total_size = _get_total_size(full_data_size, b_size, num_batch)
final_result = []
data_iterators = [
batch_iterator(args[slice_on + i][:total_size], b_size, split_over_axis)
for i in range(0, num_data)
]
for batch in data_iterators[0]:
args[slice_on] = batch
for idx in range(1, num_data):
args[slice_on + idx] = next(data_iterators[idx])
r = func(*args, **kwargs)
if r is not None:
final_result.append(r)
return _merge_results_after_batching(final_result, merge_over_axis)
|
def arg_wrapper(*args, **kwargs):
# priority: decorator > class_attribute
# by default data is in args[1:] (self needs to be taken into account)
b_size = batch_size or getattr(args[0], "batch_size", None)
# no batching if b_size is None
if b_size is None:
return func(*args, **kwargs)
args = list(args)
default_logger.debug(
f"batching enabled for {func.__qualname__} batch_size={b_size} "
f"num_batch={num_batch} axis={split_over_axis}"
)
# assume all datas have the same length
full_data_size = _get_size(args[slice_on], split_over_axis)
total_size = _get_total_size(full_data_size, b_size, num_batch)
final_result = []
data_iterators = [
batch_iterator(args[slice_on + i][:total_size], b_size, split_over_axis)
for i in range(0, num_data)
]
for batch in data_iterators[0]:
args[slice_on] = batch
for idx in range(1, num_data):
args[slice_on + idx] = next(data_iterators[idx])
r = func(*args, **kwargs)
if r is not None:
final_result.append(r)
return _merge_results_after_batching(final_result, merge_over_axis)
|
https://github.com/jina-ai/jina/issues/1229
|
Traceback (most recent call last):
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 292, in msg_callback
self.zmqlet.send_message(self._callback(msg))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 266, in _callback
self.pre_hook(msg).handle(msg).post_hook(msg)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 160, in handle
self.executor(self.request_type)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/__init__.py", line 570, in __call__
d()
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 251, in __call__
self._traverse_apply(self.req.docs, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 268, in _traverse_apply
**kwargs,
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 281, in _traverse_rec
doc.chunks, doc, 'chunks', path[1:], *args, **kwargs
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 284, in _traverse_rec
self._apply_all(docs, parent_doc, parent_edge_type, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/search.py", line 124, in _apply_all
idx, dist = self.exec_fn(embed_vecs, top_k=int(self.top_k))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/indexers/vector.py", line 279, in query
dist = self._euclidean(_keys, self.query_handler)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/decorators.py", line 241, in arg_wrapper
for b in batch_iterator(data[:total_size], b_size, split_over_axis, yield_slice=yield_slice):
TypeError: 'NoneType' object is not subscriptable
|
TypeError
|
def arg_wrapper(*args, **kwargs):
# priority: decorator > class_attribute
# by default data is in args[1] (self needs to be taken into account)
data = args[slice_on]
args = list(args)
b_size = (batch_size(data) if callable(batch_size) else batch_size) or getattr(
args[0], "batch_size", None
)
# no batching if b_size is None
if b_size is None or data is None:
return func(*args, **kwargs)
default_logger.debug(
f"batching enabled for {func.__qualname__} batch_size={b_size} "
f"num_batch={num_batch} axis={split_over_axis}"
)
full_data_size = _get_size(data, split_over_axis)
total_size = _get_total_size(full_data_size, batch_size, num_batch)
final_result = []
data = (data, args[label_on]) if label_on else data
yield_slice = isinstance(data, np.memmap)
slice_idx = None
for b in batch_iterator(
data[:total_size], b_size, split_over_axis, yield_slice=yield_slice
):
if yield_slice:
slice_idx = b
new_memmap = np.memmap(
data.filename, dtype=data.dtype, mode="r", shape=data.shape
)
b = new_memmap[slice_idx]
slice_idx = slice_idx[split_over_axis]
if slice_idx.start is None or slice_idx.stop is None:
slice_idx = None
if not isinstance(b, tuple):
# for now, keeping ordered_idx is only supported if no labels
args[slice_on] = b
if ordinal_idx_arg and slice_idx is not None:
args[ordinal_idx_arg] = slice_idx
else:
args[slice_on] = b[0]
args[label_on] = b[1]
r = func(*args, **kwargs)
if yield_slice:
del new_memmap
if r is not None:
final_result.append(r)
return _merge_results_after_batching(final_result, merge_over_axis)
|
def arg_wrapper(*args, **kwargs):
# priority: decorator > class_attribute
# by default data is in args[1] (self needs to be taken into account)
data = args[slice_on]
args = list(args)
b_size = (batch_size(data) if callable(batch_size) else batch_size) or getattr(
args[0], "batch_size", None
)
# no batching if b_size is None
if b_size is None:
return func(*args, **kwargs)
default_logger.debug(
f"batching enabled for {func.__qualname__} batch_size={b_size} "
f"num_batch={num_batch} axis={split_over_axis}"
)
full_data_size = _get_size(data, split_over_axis)
total_size = _get_total_size(full_data_size, batch_size, num_batch)
final_result = []
data = (data, args[label_on]) if label_on else data
yield_slice = isinstance(data, np.memmap)
slice_idx = None
for b in batch_iterator(
data[:total_size], b_size, split_over_axis, yield_slice=yield_slice
):
if yield_slice:
slice_idx = b
new_memmap = np.memmap(
data.filename, dtype=data.dtype, mode="r", shape=data.shape
)
b = new_memmap[slice_idx]
slice_idx = slice_idx[split_over_axis]
if slice_idx.start is None or slice_idx.stop is None:
slice_idx = None
if not isinstance(b, tuple):
# for now, keeping ordered_idx is only supported if no labels
args[slice_on] = b
if ordinal_idx_arg and slice_idx is not None:
args[ordinal_idx_arg] = slice_idx
else:
args[slice_on] = b[0]
args[label_on] = b[1]
r = func(*args, **kwargs)
if yield_slice:
del new_memmap
if r is not None:
final_result.append(r)
return _merge_results_after_batching(final_result, merge_over_axis)
|
https://github.com/jina-ai/jina/issues/1229
|
Traceback (most recent call last):
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 292, in msg_callback
self.zmqlet.send_message(self._callback(msg))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 266, in _callback
self.pre_hook(msg).handle(msg).post_hook(msg)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 160, in handle
self.executor(self.request_type)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/__init__.py", line 570, in __call__
d()
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 251, in __call__
self._traverse_apply(self.req.docs, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 268, in _traverse_apply
**kwargs,
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 281, in _traverse_rec
doc.chunks, doc, 'chunks', path[1:], *args, **kwargs
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 284, in _traverse_rec
self._apply_all(docs, parent_doc, parent_edge_type, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/search.py", line 124, in _apply_all
idx, dist = self.exec_fn(embed_vecs, top_k=int(self.top_k))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/indexers/vector.py", line 279, in query
dist = self._euclidean(_keys, self.query_handler)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/decorators.py", line 241, in arg_wrapper
for b in batch_iterator(data[:total_size], b_size, split_over_axis, yield_slice=yield_slice):
TypeError: 'NoneType' object is not subscriptable
|
TypeError
|
def batching_multi_input(
func: Callable[[Any], np.ndarray] = None,
batch_size: Union[int, Callable] = None,
num_batch: Optional[int] = None,
split_over_axis: int = 0,
merge_over_axis: int = 0,
slice_on: int = 1,
num_data: int = 1,
) -> Any:
"""Split the input of a function into small batches and call :func:`func` on each batch
, collect the merged result and return. This is useful when the input is too big to fit into memory
:param func: function to decorate
:param batch_size: size of each batch
:param num_batch: number of batches to take, the rest will be ignored
:param split_over_axis: split over which axis into batches
:param merge_over_axis: merge over which axis into a single result
:param slice_on: the location of the data. When using inside a class,
``slice_on`` should take ``self`` into consideration.
:param num_data: the number of data inside the arguments
:return: the merged result as if run :func:`func` once on the input.
..warning:
data arguments will be taken starting from ``slice_on` to ``slice_on + num_data``
Example:
.. highlight:: python
.. code-block:: python
class MultiModalExecutor:
@batching_multi_input(batch_size = 64, num_data=2)
def encode(self, *batches, **kwargs):
batch_modality0 = batches[0]
embed0 = _encode_modality(batch_modality0)
batch_modality1 = batches[1]
embed1 = _encode_modality(batch_modality0)
"""
def _batching(func):
@wraps(func)
def arg_wrapper(*args, **kwargs):
data = args[slice_on]
# priority: decorator > class_attribute
# by default data is in args[1:] (self needs to be taken into account)
b_size = batch_size or getattr(args[0], "batch_size", None)
# no batching if b_size is None
if b_size is None or data is None:
return func(*args, **kwargs)
args = list(args)
default_logger.debug(
f"batching enabled for {func.__qualname__} batch_size={b_size} "
f"num_batch={num_batch} axis={split_over_axis}"
)
# assume all datas have the same length
full_data_size = _get_size(args[slice_on], split_over_axis)
total_size = _get_total_size(full_data_size, b_size, num_batch)
final_result = []
data_iterators = [
batch_iterator(args[slice_on + i][:total_size], b_size, split_over_axis)
for i in range(0, num_data)
]
for batch in data_iterators[0]:
args[slice_on] = batch
for idx in range(1, num_data):
args[slice_on + idx] = next(data_iterators[idx])
r = func(*args, **kwargs)
if r is not None:
final_result.append(r)
return _merge_results_after_batching(final_result, merge_over_axis)
return arg_wrapper
if func:
return _batching(func)
else:
return _batching
|
def batching_multi_input(
func: Callable[[Any], np.ndarray] = None,
batch_size: Union[int, Callable] = None,
num_batch: Optional[int] = None,
split_over_axis: int = 0,
merge_over_axis: int = 0,
slice_on: int = 1,
num_data: int = 1,
) -> Any:
"""Split the input of a function into small batches and call :func:`func` on each batch
, collect the merged result and return. This is useful when the input is too big to fit into memory
:param func: function to decorate
:param batch_size: size of each batch
:param num_batch: number of batches to take, the rest will be ignored
:param split_over_axis: split over which axis into batches
:param merge_over_axis: merge over which axis into a single result
:param slice_on: the location of the data. When using inside a class,
``slice_on`` should take ``self`` into consideration.
:param num_data: the number of data inside the arguments
:return: the merged result as if run :func:`func` once on the input.
..warning:
data arguments will be taken starting from ``slice_on` to ``slice_on + num_data``
Example:
.. highlight:: python
.. code-block:: python
class MultiModalExecutor:
@batching_multi_input(batch_size = 64, num_data=2)
def encode(self, *batches, **kwargs):
batch_modality0 = batches[0]
embed0 = _encode_modality(batch_modality0)
batch_modality1 = batches[1]
embed1 = _encode_modality(batch_modality0)
"""
def _batching(func):
@wraps(func)
def arg_wrapper(*args, **kwargs):
# priority: decorator > class_attribute
# by default data is in args[1:] (self needs to be taken into account)
b_size = batch_size or getattr(args[0], "batch_size", None)
# no batching if b_size is None
if b_size is None:
return func(*args, **kwargs)
args = list(args)
default_logger.debug(
f"batching enabled for {func.__qualname__} batch_size={b_size} "
f"num_batch={num_batch} axis={split_over_axis}"
)
# assume all datas have the same length
full_data_size = _get_size(args[slice_on], split_over_axis)
total_size = _get_total_size(full_data_size, b_size, num_batch)
final_result = []
data_iterators = [
batch_iterator(args[slice_on + i][:total_size], b_size, split_over_axis)
for i in range(0, num_data)
]
for batch in data_iterators[0]:
args[slice_on] = batch
for idx in range(1, num_data):
args[slice_on + idx] = next(data_iterators[idx])
r = func(*args, **kwargs)
if r is not None:
final_result.append(r)
return _merge_results_after_batching(final_result, merge_over_axis)
return arg_wrapper
if func:
return _batching(func)
else:
return _batching
|
https://github.com/jina-ai/jina/issues/1229
|
Traceback (most recent call last):
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 292, in msg_callback
self.zmqlet.send_message(self._callback(msg))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 266, in _callback
self.pre_hook(msg).handle(msg).post_hook(msg)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 160, in handle
self.executor(self.request_type)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/__init__.py", line 570, in __call__
d()
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 251, in __call__
self._traverse_apply(self.req.docs, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 268, in _traverse_apply
**kwargs,
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 281, in _traverse_rec
doc.chunks, doc, 'chunks', path[1:], *args, **kwargs
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 284, in _traverse_rec
self._apply_all(docs, parent_doc, parent_edge_type, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/search.py", line 124, in _apply_all
idx, dist = self.exec_fn(embed_vecs, top_k=int(self.top_k))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/indexers/vector.py", line 279, in query
dist = self._euclidean(_keys, self.query_handler)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/decorators.py", line 241, in arg_wrapper
for b in batch_iterator(data[:total_size], b_size, split_over_axis, yield_slice=yield_slice):
TypeError: 'NoneType' object is not subscriptable
|
TypeError
|
def _batching(func):
@wraps(func)
def arg_wrapper(*args, **kwargs):
data = args[slice_on]
# priority: decorator > class_attribute
# by default data is in args[1:] (self needs to be taken into account)
b_size = batch_size or getattr(args[0], "batch_size", None)
# no batching if b_size is None
if b_size is None or data is None:
return func(*args, **kwargs)
args = list(args)
default_logger.debug(
f"batching enabled for {func.__qualname__} batch_size={b_size} "
f"num_batch={num_batch} axis={split_over_axis}"
)
# assume all datas have the same length
full_data_size = _get_size(args[slice_on], split_over_axis)
total_size = _get_total_size(full_data_size, b_size, num_batch)
final_result = []
data_iterators = [
batch_iterator(args[slice_on + i][:total_size], b_size, split_over_axis)
for i in range(0, num_data)
]
for batch in data_iterators[0]:
args[slice_on] = batch
for idx in range(1, num_data):
args[slice_on + idx] = next(data_iterators[idx])
r = func(*args, **kwargs)
if r is not None:
final_result.append(r)
return _merge_results_after_batching(final_result, merge_over_axis)
return arg_wrapper
|
def _batching(func):
@wraps(func)
def arg_wrapper(*args, **kwargs):
# priority: decorator > class_attribute
# by default data is in args[1:] (self needs to be taken into account)
b_size = batch_size or getattr(args[0], "batch_size", None)
# no batching if b_size is None
if b_size is None:
return func(*args, **kwargs)
args = list(args)
default_logger.debug(
f"batching enabled for {func.__qualname__} batch_size={b_size} "
f"num_batch={num_batch} axis={split_over_axis}"
)
# assume all datas have the same length
full_data_size = _get_size(args[slice_on], split_over_axis)
total_size = _get_total_size(full_data_size, b_size, num_batch)
final_result = []
data_iterators = [
batch_iterator(args[slice_on + i][:total_size], b_size, split_over_axis)
for i in range(0, num_data)
]
for batch in data_iterators[0]:
args[slice_on] = batch
for idx in range(1, num_data):
args[slice_on + idx] = next(data_iterators[idx])
r = func(*args, **kwargs)
if r is not None:
final_result.append(r)
return _merge_results_after_batching(final_result, merge_over_axis)
return arg_wrapper
|
https://github.com/jina-ai/jina/issues/1229
|
Traceback (most recent call last):
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 292, in msg_callback
self.zmqlet.send_message(self._callback(msg))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 266, in _callback
self.pre_hook(msg).handle(msg).post_hook(msg)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 160, in handle
self.executor(self.request_type)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/__init__.py", line 570, in __call__
d()
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 251, in __call__
self._traverse_apply(self.req.docs, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 268, in _traverse_apply
**kwargs,
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 281, in _traverse_rec
doc.chunks, doc, 'chunks', path[1:], *args, **kwargs
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 284, in _traverse_rec
self._apply_all(docs, parent_doc, parent_edge_type, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/search.py", line 124, in _apply_all
idx, dist = self.exec_fn(embed_vecs, top_k=int(self.top_k))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/indexers/vector.py", line 279, in query
dist = self._euclidean(_keys, self.query_handler)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/decorators.py", line 241, in arg_wrapper
for b in batch_iterator(data[:total_size], b_size, split_over_axis, yield_slice=yield_slice):
TypeError: 'NoneType' object is not subscriptable
|
TypeError
|
def query(
self, keys: "np.ndarray", top_k: int, *args, **kwargs
) -> Tuple[Optional["np.ndarray"], Optional["np.ndarray"]]:
"""Find the top-k vectors with smallest ``metric`` and return their ids in ascending order.
:return: a tuple of two ndarray.
The first is ids in shape B x K (`dtype=int`), the second is metric in shape B x K (`dtype=float`)
.. warning::
This operation is memory-consuming.
Distance (the smaller the better) is returned, not the score.
"""
if self.size == 0:
return None, None
if self.metric not in {"cosine", "euclidean"} or self.backend == "scipy":
dist = self._cdist(keys, self.query_handler)
elif self.metric == "euclidean":
_keys = _ext_A(keys)
dist = self._euclidean(_keys, self.query_handler)
elif self.metric == "cosine":
_keys = _ext_A(_norm(keys))
dist = self._cosine(_keys, self.query_handler)
else:
raise NotImplementedError(f"{self.metric} is not implemented")
idx, dist = self._get_sorted_top_k(dist, top_k)
return self.int2ext_id[idx], dist
|
def query(
self, keys: "np.ndarray", top_k: int, *args, **kwargs
) -> Tuple["np.ndarray", "np.ndarray"]:
"""Find the top-k vectors with smallest ``metric`` and return their ids in ascending order.
:return: a tuple of two ndarray.
The first is ids in shape B x K (`dtype=int`), the second is metric in shape B x K (`dtype=float`)
.. warning::
This operation is memory-consuming.
Distance (the smaller the better) is returned, not the score.
"""
if self.metric not in {"cosine", "euclidean"} or self.backend == "scipy":
dist = self._cdist(keys, self.query_handler)
elif self.metric == "euclidean":
_keys = _ext_A(keys)
dist = self._euclidean(_keys, self.query_handler)
elif self.metric == "cosine":
_keys = _ext_A(_norm(keys))
dist = self._cosine(_keys, self.query_handler)
else:
raise NotImplementedError(f"{self.metric} is not implemented")
idx, dist = self._get_sorted_top_k(dist, top_k)
return self.int2ext_id[idx], dist
|
https://github.com/jina-ai/jina/issues/1229
|
Traceback (most recent call last):
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 292, in msg_callback
self.zmqlet.send_message(self._callback(msg))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 266, in _callback
self.pre_hook(msg).handle(msg).post_hook(msg)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/peapods/pea.py", line 160, in handle
self.executor(self.request_type)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/__init__.py", line 570, in __call__
d()
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 251, in __call__
self._traverse_apply(self.req.docs, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 268, in _traverse_apply
**kwargs,
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 281, in _traverse_rec
doc.chunks, doc, 'chunks', path[1:], *args, **kwargs
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/__init__.py", line 284, in _traverse_rec
self._apply_all(docs, parent_doc, parent_edge_type, *args, **kwargs)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/drivers/search.py", line 124, in _apply_all
idx, dist = self.exec_fn(embed_vecs, top_k=int(self.top_k))
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/indexers/vector.py", line 279, in query
dist = self._euclidean(_keys, self.query_handler)
File "/home/cristian/envs/lyrics/lib/python3.7/site-packages/jina/executors/decorators.py", line 241, in arg_wrapper
for b in batch_iterator(data[:total_size], b_size, split_over_axis, yield_slice=yield_slice):
TypeError: 'NoneType' object is not subscriptable
|
TypeError
|
def resolve_filter_field(
self, auto_schema, model, filterset_class, field_name, filter_field
):
from django_filters.rest_framework import filters
unambiguous_mapping = {
filters.CharFilter: OpenApiTypes.STR,
filters.BooleanFilter: OpenApiTypes.BOOL,
filters.DateFilter: OpenApiTypes.DATE,
filters.DateTimeFilter: OpenApiTypes.DATETIME,
filters.IsoDateTimeFilter: OpenApiTypes.DATETIME,
filters.TimeFilter: OpenApiTypes.TIME,
filters.UUIDFilter: OpenApiTypes.UUID,
filters.DurationFilter: OpenApiTypes.DURATION,
filters.OrderingFilter: OpenApiTypes.STR,
filters.TimeRangeFilter: OpenApiTypes.TIME,
filters.DateFromToRangeFilter: OpenApiTypes.DATE,
filters.IsoDateTimeFromToRangeFilter: OpenApiTypes.DATETIME,
filters.DateTimeFromToRangeFilter: OpenApiTypes.DATETIME,
}
if isinstance(filter_field, tuple(unambiguous_mapping)):
for cls in filter_field.__class__.__mro__:
if cls in unambiguous_mapping:
schema = build_basic_type(unambiguous_mapping[cls])
break
elif isinstance(filter_field, (filters.NumberFilter, filters.NumericRangeFilter)):
# NumberField is underspecified by itself. try to find the
# type that makes the most sense or default to generic NUMBER
if filter_field.method:
schema = self._build_filter_method_type(filterset_class, filter_field)
if schema["type"] not in ["integer", "number"]:
schema = build_basic_type(OpenApiTypes.NUMBER)
else:
model_field = self._get_model_field(filter_field, model)
if isinstance(model_field, (models.IntegerField, models.AutoField)):
schema = build_basic_type(OpenApiTypes.INT)
elif isinstance(model_field, models.FloatField):
schema = build_basic_type(OpenApiTypes.FLOAT)
elif isinstance(model_field, models.DecimalField):
schema = build_basic_type(OpenApiTypes.NUMBER) # TODO may be improved
else:
schema = build_basic_type(OpenApiTypes.NUMBER)
elif filter_field.method:
# try to make best effort on the given method
schema = self._build_filter_method_type(filterset_class, filter_field)
else:
# last resort is to lookup the type via the model field.
model_field = self._get_model_field(filter_field, model)
if isinstance(model_field, models.Field):
try:
schema = auto_schema._map_model_field(model_field, direction=None)
except Exception as exc:
warn(
f"Exception raised while trying resolve model field for django-filter "
f'field "{field_name}". Defaulting to string (Exception: {exc})'
)
schema = build_basic_type(OpenApiTypes.STR)
else:
# default to string if nothing else works
schema = build_basic_type(OpenApiTypes.STR)
# primary keys are usually non-editable (readOnly=True) and map_model_field correctly
# signals that attribute. however this does not apply in this context.
schema.pop("readOnly", None)
# enrich schema with additional info from filter_field
enum = schema.pop("enum", None)
if "choices" in filter_field.extra:
enum = [c for c, _ in filter_field.extra["choices"]]
if enum:
schema["enum"] = sorted(enum, key=str)
description = schema.pop("description", None)
if filter_field.extra.get("help_text", None):
description = filter_field.extra["help_text"]
elif filter_field.label is not None:
description = filter_field.label
# parameter style variations based on filter base class
if isinstance(filter_field, filters.BaseCSVFilter):
schema = build_array_type(schema)
field_names = [field_name]
explode = False
style = "form"
elif isinstance(filter_field, filters.MultipleChoiceFilter):
schema = build_array_type(schema)
field_names = [field_name]
explode = True
style = "form"
elif isinstance(filter_field, (filters.RangeFilter, filters.NumericRangeFilter)):
field_names = [f"{field_name}_min", f"{field_name}_max"]
explode = None
style = None
else:
field_names = [field_name]
explode = None
style = None
return [
build_parameter_type(
name=field_name,
required=filter_field.extra["required"],
location=OpenApiParameter.QUERY,
description=description,
schema=schema,
explode=explode,
style=style,
)
for field_name in field_names
]
|
def resolve_filter_field(
self, auto_schema, model, filterset_class, field_name, filter_field
):
from django_filters.rest_framework import filters
unambiguous_mapping = {
filters.CharFilter: OpenApiTypes.STR,
filters.BooleanFilter: OpenApiTypes.BOOL,
filters.DateFilter: OpenApiTypes.DATE,
filters.DateTimeFilter: OpenApiTypes.DATETIME,
filters.IsoDateTimeFilter: OpenApiTypes.DATETIME,
filters.TimeFilter: OpenApiTypes.TIME,
filters.UUIDFilter: OpenApiTypes.UUID,
filters.DurationFilter: OpenApiTypes.DURATION,
filters.OrderingFilter: OpenApiTypes.STR,
filters.TimeRangeFilter: OpenApiTypes.TIME,
filters.DateFromToRangeFilter: OpenApiTypes.DATE,
filters.IsoDateTimeFromToRangeFilter: OpenApiTypes.DATETIME,
filters.DateTimeFromToRangeFilter: OpenApiTypes.DATETIME,
}
if isinstance(filter_field, tuple(unambiguous_mapping)):
for cls in filter_field.__class__.__mro__:
if cls in unambiguous_mapping:
schema = build_basic_type(unambiguous_mapping[cls])
break
elif isinstance(filter_field, (filters.NumberFilter, filters.NumericRangeFilter)):
# NumberField is underspecified by itself. try to find the
# type that makes the most sense or default to generic NUMBER
if filter_field.method:
schema = self._build_filter_method_type(filterset_class, filter_field)
if schema["type"] not in ["integer", "number"]:
schema = build_basic_type(OpenApiTypes.NUMBER)
else:
model_field = self._get_model_field(filter_field, model)
if isinstance(model_field, (models.IntegerField, models.AutoField)):
schema = build_basic_type(OpenApiTypes.INT)
elif isinstance(model_field, models.FloatField):
schema = build_basic_type(OpenApiTypes.FLOAT)
elif isinstance(model_field, models.DecimalField):
schema = build_basic_type(OpenApiTypes.NUMBER) # TODO may be improved
else:
schema = build_basic_type(OpenApiTypes.NUMBER)
elif filter_field.method:
# try to make best effort on the given method
schema = self._build_filter_method_type(filterset_class, filter_field)
else:
# last resort is to lookup the type via the model field.
model_field = self._get_model_field(filter_field, model)
if isinstance(model_field, models.Field):
try:
schema = auto_schema._map_model_field(model_field, direction=None)
except Exception as exc:
warn(
f"Exception raised while trying resolve model field for django-filter "
f'field "{field_name}". Defaulting to string (Exception: {exc})'
)
schema = build_basic_type(OpenApiTypes.STR)
else:
# default to string if nothing else works
schema = build_basic_type(OpenApiTypes.STR)
# enrich schema with additional info from filter_field
enum = schema.pop("enum", None)
if "choices" in filter_field.extra:
enum = [c for c, _ in filter_field.extra["choices"]]
if enum:
schema["enum"] = sorted(enum, key=str)
description = schema.pop("description", None)
if filter_field.extra.get("help_text", None):
description = filter_field.extra["help_text"]
elif filter_field.label is not None:
description = filter_field.label
# parameter style variations based on filter base class
if isinstance(filter_field, filters.BaseCSVFilter):
schema = build_array_type(schema)
field_names = [field_name]
explode = False
style = "form"
elif isinstance(filter_field, filters.MultipleChoiceFilter):
schema = build_array_type(schema)
field_names = [field_name]
explode = True
style = "form"
elif isinstance(filter_field, (filters.RangeFilter, filters.NumericRangeFilter)):
field_names = [f"{field_name}_min", f"{field_name}_max"]
explode = None
style = None
else:
field_names = [field_name]
explode = None
style = None
return [
build_parameter_type(
name=field_name,
required=filter_field.extra["required"],
location=OpenApiParameter.QUERY,
description=description,
schema=schema,
explode=explode,
style=style,
)
for field_name in field_names
]
|
https://github.com/tfranzel/drf-spectacular/issues/323
|
Warning #1: could not resolve field on model <class 'test_spectacular.models.TestModel'> with path "reltd_set". this is likely a custom field that does some unknown magic. maybe consider annotating the field/property? defaulting to "string". (Exception: TestModel has no field named 'reltd_set')
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
main()
File "./manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "test_spectacular/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "test_spectacular/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "test_spectacular/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "test_spectacular/venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/management/commands/spectacular.py", line 50, in handle
schema = generator.get_schema(request=None, public=True)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/generators.py", line 219, in get_schema
paths=self.parse(request, public),
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/generators.py", line 196, in parse
operation = view.schema.get_operation(path, path_regex, method, self.registry)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 83, in get_operation
operation['responses'] = self._get_response_bodies()
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 969, in _get_response_bodies
return {'200': self._get_response_for_code(response_serializers, '200')}
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 1007, in _get_response_for_code
component = self.resolve_serializer(serializer, 'response')
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 1146, in resolve_serializer
component.schema = self._map_serializer(serializer, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 669, in _map_serializer
schema = self._map_basic_serializer(serializer, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 736, in _map_basic_serializer
schema = self._map_serializer_field(field, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 488, in _map_serializer_field
schema = self._map_serializer_field(field.child_relation, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 516, in _map_serializer_field
schema = self._map_model_field(model_field, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 387, in _map_model_field
assert isinstance(model_field, models.Field)
AssertionError
|
AssertionError
|
def _map_serializer_field(self, field, direction, collect_meta=True):
if collect_meta:
meta = self._get_serializer_field_meta(field)
else:
meta = {}
if has_override(field, "field"):
override = get_override(field, "field")
if is_basic_type(override):
schema = build_basic_type(override)
if schema is None:
return None
elif isinstance(override, dict):
schema = override
else:
schema = self._map_serializer_field(
force_instance(override), direction, False
)
field_component_name = get_override(field, "field_component_name")
if field_component_name:
component = ResolvedComponent(
name=field_component_name,
type=ResolvedComponent.SCHEMA,
schema=schema,
object=field,
)
self.registry.register_on_missing(component)
return append_meta(component.ref, meta)
else:
return append_meta(schema, meta)
serializer_field_extension = OpenApiSerializerFieldExtension.get_match(field)
if serializer_field_extension:
schema = serializer_field_extension.map_serializer_field(self, direction)
return append_meta(schema, meta)
# nested serializer with many=True gets automatically replaced with ListSerializer
if is_list_serializer(field):
if is_serializer(field.child):
component = self.resolve_serializer(field.child, direction)
return (
append_meta(build_array_type(component.ref), meta)
if component
else None
)
else:
schema = self._map_serializer_field(field.child, direction, collect_meta)
return append_meta(build_array_type(schema), meta)
# nested serializer
if is_serializer(field):
component = self.resolve_serializer(field, direction)
return append_meta(component.ref, meta) if component else None
# Related fields.
if isinstance(field, serializers.ManyRelatedField):
schema = self._map_serializer_field(
field.child_relation, direction, collect_meta
)
# remove hand-over initkwargs applying only to outer scope
schema.pop("description", None)
schema.pop("readOnly", None)
return append_meta(build_array_type(schema), meta)
if isinstance(field, serializers.PrimaryKeyRelatedField):
# read_only fields do not have a Manager by design. go around and get field
# from parent. also avoid calling Manager. __bool__ as it might be customized
# to hit the database.
if getattr(field, "queryset", None) is not None:
model_field = field.queryset.model._meta.pk
else:
if isinstance(field.parent, serializers.ManyRelatedField):
model = field.parent.parent.Meta.model
source = field.parent.source.split(".")
else:
model = field.parent.Meta.model
source = field.source.split(".")
# estimates the relating model field and jumps to it's target model PK field.
# also differentiate as source can be direct (pk) or relation field (model).
model_field = follow_field_source(model, source)
if callable(model_field):
# follow_field_source bailed with a warning. be graceful and default to str.
model_field = models.TextField()
# primary keys are usually non-editable (readOnly=True) and map_model_field correctly
# signals that attribute. however this does not apply in the context of relations.
schema = self._map_model_field(model_field, direction)
schema.pop("readOnly", None)
return append_meta(schema, meta)
if isinstance(field, serializers.StringRelatedField):
return append_meta(build_basic_type(OpenApiTypes.STR), meta)
if isinstance(field, serializers.SlugRelatedField):
return append_meta(build_basic_type(OpenApiTypes.STR), meta)
if isinstance(field, serializers.HyperlinkedIdentityField):
return append_meta(build_basic_type(OpenApiTypes.URI), meta)
if isinstance(field, serializers.HyperlinkedRelatedField):
return append_meta(build_basic_type(OpenApiTypes.URI), meta)
if isinstance(field, serializers.MultipleChoiceField):
return append_meta(build_array_type(build_choice_field(field)), meta)
if isinstance(field, serializers.ChoiceField):
return append_meta(build_choice_field(field), meta)
if isinstance(field, serializers.ListField):
if isinstance(field.child, _UnvalidatedField):
return append_meta(build_array_type({}), meta)
elif is_serializer(field.child):
component = self.resolve_serializer(field.child, direction)
return (
append_meta(build_array_type(component.ref), meta)
if component
else None
)
else:
schema = self._map_serializer_field(field.child, direction, collect_meta)
return append_meta(build_array_type(schema), meta)
# DateField and DateTimeField type is string
if isinstance(field, serializers.DateField):
return append_meta(build_basic_type(OpenApiTypes.DATE), meta)
if isinstance(field, serializers.DateTimeField):
return append_meta(build_basic_type(OpenApiTypes.DATETIME), meta)
if isinstance(field, serializers.TimeField):
return append_meta(build_basic_type(OpenApiTypes.TIME), meta)
if isinstance(field, serializers.EmailField):
return append_meta(build_basic_type(OpenApiTypes.EMAIL), meta)
if isinstance(field, serializers.URLField):
return append_meta(build_basic_type(OpenApiTypes.URI), meta)
if isinstance(field, serializers.UUIDField):
return append_meta(build_basic_type(OpenApiTypes.UUID), meta)
if isinstance(field, serializers.DurationField):
return append_meta(build_basic_type(OpenApiTypes.STR), meta)
if isinstance(field, serializers.IPAddressField):
# TODO this might be a DRF bug. protocol is not propagated to serializer although it
# should have been. results in always 'both' (thus no format)
if "ipv4" == field.protocol.lower():
schema = build_basic_type(OpenApiTypes.IP4)
elif "ipv6" == field.protocol.lower():
schema = build_basic_type(OpenApiTypes.IP6)
else:
schema = build_basic_type(OpenApiTypes.STR)
return append_meta(schema, meta)
# DecimalField has multipleOf based on decimal_places
if isinstance(field, serializers.DecimalField):
if getattr(field, "coerce_to_string", api_settings.COERCE_DECIMAL_TO_STRING):
content = {**build_basic_type(OpenApiTypes.STR), "format": "decimal"}
else:
content = build_basic_type(OpenApiTypes.DECIMAL)
if field.max_whole_digits:
content["maximum"] = int(field.max_whole_digits * "9") + 1
content["minimum"] = -content["maximum"]
self._map_min_max(field, content)
return append_meta(content, meta)
if isinstance(field, serializers.FloatField):
content = build_basic_type(OpenApiTypes.FLOAT)
self._map_min_max(field, content)
return append_meta(content, meta)
if isinstance(field, serializers.IntegerField):
content = build_basic_type(OpenApiTypes.INT)
self._map_min_max(field, content)
# 2147483647 is max for int32_size, so we use int64 for format
if (
int(content.get("maximum", 0)) > 2147483647
or int(content.get("minimum", 0)) > 2147483647
):
content["format"] = "int64"
return append_meta(content, meta)
if isinstance(field, serializers.FileField):
if spectacular_settings.COMPONENT_SPLIT_REQUEST and direction == "request":
content = build_basic_type(OpenApiTypes.BINARY)
else:
use_url = getattr(field, "use_url", api_settings.UPLOADED_FILES_USE_URL)
content = build_basic_type(
OpenApiTypes.URI if use_url else OpenApiTypes.STR
)
return append_meta(content, meta)
if isinstance(field, serializers.SerializerMethodField):
method = getattr(field.parent, field.method_name)
return append_meta(self._map_response_type_hint(method), meta)
if anyisinstance(field, [serializers.BooleanField, serializers.NullBooleanField]):
return append_meta(build_basic_type(OpenApiTypes.BOOL), meta)
if isinstance(field, serializers.JSONField):
return append_meta(build_basic_type(OpenApiTypes.OBJECT), meta)
if anyisinstance(field, [serializers.DictField, serializers.HStoreField]):
content = build_basic_type(OpenApiTypes.OBJECT)
if not isinstance(field.child, _UnvalidatedField):
content["additionalProperties"] = self._map_serializer_field(
field.child, direction, collect_meta
)
return append_meta(content, meta)
if isinstance(field, serializers.CharField):
return append_meta(build_basic_type(OpenApiTypes.STR), meta)
if isinstance(field, serializers.ReadOnlyField):
# direct source from the serializer
assert field.source_attrs, f'ReadOnlyField "{field}" needs a proper source'
target = follow_field_source(field.parent.Meta.model, field.source_attrs)
if callable(target):
schema = self._map_response_type_hint(target)
elif isinstance(target, models.Field):
schema = self._map_model_field(target, direction)
else:
assert False, (
f'ReadOnlyField target "{field}" must be property or model field'
)
return append_meta(schema, meta)
# DRF was not able to match the model field to an explicit SerializerField and therefore
# used its generic fallback serializer field that simply wraps the model field.
if isinstance(field, serializers.ModelField):
schema = self._map_model_field(field.model_field, direction)
return append_meta(schema, meta)
warn(f'could not resolve serializer field "{field}". defaulting to "string"')
return append_meta(build_basic_type(OpenApiTypes.STR), meta)
|
def _map_serializer_field(self, field, direction, collect_meta=True):
if collect_meta:
meta = self._get_serializer_field_meta(field)
else:
meta = {}
if has_override(field, "field"):
override = get_override(field, "field")
if is_basic_type(override):
schema = build_basic_type(override)
if schema is None:
return None
elif isinstance(override, dict):
schema = override
else:
schema = self._map_serializer_field(
force_instance(override), direction, False
)
field_component_name = get_override(field, "field_component_name")
if field_component_name:
component = ResolvedComponent(
name=field_component_name,
type=ResolvedComponent.SCHEMA,
schema=schema,
object=field,
)
self.registry.register_on_missing(component)
return append_meta(component.ref, meta)
else:
return append_meta(schema, meta)
serializer_field_extension = OpenApiSerializerFieldExtension.get_match(field)
if serializer_field_extension:
schema = serializer_field_extension.map_serializer_field(self, direction)
return append_meta(schema, meta)
# nested serializer with many=True gets automatically replaced with ListSerializer
if is_list_serializer(field):
if is_serializer(field.child):
component = self.resolve_serializer(field.child, direction)
return (
append_meta(build_array_type(component.ref), meta)
if component
else None
)
else:
schema = self._map_serializer_field(field.child, direction, collect_meta)
return append_meta(build_array_type(schema), meta)
# nested serializer
if is_serializer(field):
component = self.resolve_serializer(field, direction)
return append_meta(component.ref, meta) if component else None
# Related fields.
if isinstance(field, serializers.ManyRelatedField):
schema = self._map_serializer_field(
field.child_relation, direction, collect_meta
)
# remove hand-over initkwargs applying only to outer scope
schema.pop("description", None)
schema.pop("readOnly", None)
return append_meta(build_array_type(schema), meta)
if isinstance(field, serializers.PrimaryKeyRelatedField):
# read_only fields do not have a Manager by design. go around and get field
# from parent. also avoid calling Manager. __bool__ as it might be customized
# to hit the database.
if getattr(field, "queryset", None) is not None:
model_field = field.queryset.model._meta.pk
else:
if isinstance(field.parent, serializers.ManyRelatedField):
model = field.parent.parent.Meta.model
source = field.parent.source.split(".")
else:
model = field.parent.Meta.model
source = field.source.split(".")
# estimates the relating model field and jumps to it's target model PK field.
# also differentiate as source can be direct (pk) or relation field (model).
model_field = follow_field_source(model, source)
if anyisinstance(model_field, [models.ForeignKey, models.ManyToManyField]):
model_field = model_field.target_field
# primary keys are usually non-editable (readOnly=True) and map_model_field correctly
# signals that attribute. however this does not apply in the context of relations.
schema = self._map_model_field(model_field, direction)
schema.pop("readOnly", None)
return append_meta(schema, meta)
if isinstance(field, serializers.StringRelatedField):
return append_meta(build_basic_type(OpenApiTypes.STR), meta)
if isinstance(field, serializers.SlugRelatedField):
return append_meta(build_basic_type(OpenApiTypes.STR), meta)
if isinstance(field, serializers.HyperlinkedIdentityField):
return append_meta(build_basic_type(OpenApiTypes.URI), meta)
if isinstance(field, serializers.HyperlinkedRelatedField):
return append_meta(build_basic_type(OpenApiTypes.URI), meta)
if isinstance(field, serializers.MultipleChoiceField):
return append_meta(build_array_type(build_choice_field(field)), meta)
if isinstance(field, serializers.ChoiceField):
return append_meta(build_choice_field(field), meta)
if isinstance(field, serializers.ListField):
if isinstance(field.child, _UnvalidatedField):
return append_meta(build_array_type({}), meta)
elif is_serializer(field.child):
component = self.resolve_serializer(field.child, direction)
return (
append_meta(build_array_type(component.ref), meta)
if component
else None
)
else:
schema = self._map_serializer_field(field.child, direction, collect_meta)
return append_meta(build_array_type(schema), meta)
# DateField and DateTimeField type is string
if isinstance(field, serializers.DateField):
return append_meta(build_basic_type(OpenApiTypes.DATE), meta)
if isinstance(field, serializers.DateTimeField):
return append_meta(build_basic_type(OpenApiTypes.DATETIME), meta)
if isinstance(field, serializers.TimeField):
return append_meta(build_basic_type(OpenApiTypes.TIME), meta)
if isinstance(field, serializers.EmailField):
return append_meta(build_basic_type(OpenApiTypes.EMAIL), meta)
if isinstance(field, serializers.URLField):
return append_meta(build_basic_type(OpenApiTypes.URI), meta)
if isinstance(field, serializers.UUIDField):
return append_meta(build_basic_type(OpenApiTypes.UUID), meta)
if isinstance(field, serializers.DurationField):
return append_meta(build_basic_type(OpenApiTypes.STR), meta)
if isinstance(field, serializers.IPAddressField):
# TODO this might be a DRF bug. protocol is not propagated to serializer although it
# should have been. results in always 'both' (thus no format)
if "ipv4" == field.protocol.lower():
schema = build_basic_type(OpenApiTypes.IP4)
elif "ipv6" == field.protocol.lower():
schema = build_basic_type(OpenApiTypes.IP6)
else:
schema = build_basic_type(OpenApiTypes.STR)
return append_meta(schema, meta)
# DecimalField has multipleOf based on decimal_places
if isinstance(field, serializers.DecimalField):
if getattr(field, "coerce_to_string", api_settings.COERCE_DECIMAL_TO_STRING):
content = {**build_basic_type(OpenApiTypes.STR), "format": "decimal"}
else:
content = build_basic_type(OpenApiTypes.DECIMAL)
if field.max_whole_digits:
content["maximum"] = int(field.max_whole_digits * "9") + 1
content["minimum"] = -content["maximum"]
self._map_min_max(field, content)
return append_meta(content, meta)
if isinstance(field, serializers.FloatField):
content = build_basic_type(OpenApiTypes.FLOAT)
self._map_min_max(field, content)
return append_meta(content, meta)
if isinstance(field, serializers.IntegerField):
content = build_basic_type(OpenApiTypes.INT)
self._map_min_max(field, content)
# 2147483647 is max for int32_size, so we use int64 for format
if (
int(content.get("maximum", 0)) > 2147483647
or int(content.get("minimum", 0)) > 2147483647
):
content["format"] = "int64"
return append_meta(content, meta)
if isinstance(field, serializers.FileField):
if spectacular_settings.COMPONENT_SPLIT_REQUEST and direction == "request":
content = build_basic_type(OpenApiTypes.BINARY)
else:
use_url = getattr(field, "use_url", api_settings.UPLOADED_FILES_USE_URL)
content = build_basic_type(
OpenApiTypes.URI if use_url else OpenApiTypes.STR
)
return append_meta(content, meta)
if isinstance(field, serializers.SerializerMethodField):
method = getattr(field.parent, field.method_name)
return append_meta(self._map_response_type_hint(method), meta)
if anyisinstance(field, [serializers.BooleanField, serializers.NullBooleanField]):
return append_meta(build_basic_type(OpenApiTypes.BOOL), meta)
if isinstance(field, serializers.JSONField):
return append_meta(build_basic_type(OpenApiTypes.OBJECT), meta)
if anyisinstance(field, [serializers.DictField, serializers.HStoreField]):
content = build_basic_type(OpenApiTypes.OBJECT)
if not isinstance(field.child, _UnvalidatedField):
content["additionalProperties"] = self._map_serializer_field(
field.child, direction, collect_meta
)
return append_meta(content, meta)
if isinstance(field, serializers.CharField):
return append_meta(build_basic_type(OpenApiTypes.STR), meta)
if isinstance(field, serializers.ReadOnlyField):
# direct source from the serializer
assert field.source_attrs, f'ReadOnlyField "{field}" needs a proper source'
target = follow_field_source(field.parent.Meta.model, field.source_attrs)
if callable(target):
schema = self._map_response_type_hint(target)
elif isinstance(target, models.Field):
schema = self._map_model_field(target, direction)
else:
assert False, (
f'ReadOnlyField target "{field}" must be property or model field'
)
return append_meta(schema, meta)
# DRF was not able to match the model field to an explicit SerializerField and therefore
# used its generic fallback serializer field that simply wraps the model field.
if isinstance(field, serializers.ModelField):
schema = self._map_model_field(field.model_field, direction)
return append_meta(schema, meta)
warn(f'could not resolve serializer field "{field}". defaulting to "string"')
return append_meta(build_basic_type(OpenApiTypes.STR), meta)
|
https://github.com/tfranzel/drf-spectacular/issues/323
|
Warning #1: could not resolve field on model <class 'test_spectacular.models.TestModel'> with path "reltd_set". this is likely a custom field that does some unknown magic. maybe consider annotating the field/property? defaulting to "string". (Exception: TestModel has no field named 'reltd_set')
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
main()
File "./manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "test_spectacular/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "test_spectacular/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "test_spectacular/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "test_spectacular/venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/management/commands/spectacular.py", line 50, in handle
schema = generator.get_schema(request=None, public=True)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/generators.py", line 219, in get_schema
paths=self.parse(request, public),
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/generators.py", line 196, in parse
operation = view.schema.get_operation(path, path_regex, method, self.registry)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 83, in get_operation
operation['responses'] = self._get_response_bodies()
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 969, in _get_response_bodies
return {'200': self._get_response_for_code(response_serializers, '200')}
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 1007, in _get_response_for_code
component = self.resolve_serializer(serializer, 'response')
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 1146, in resolve_serializer
component.schema = self._map_serializer(serializer, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 669, in _map_serializer
schema = self._map_basic_serializer(serializer, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 736, in _map_basic_serializer
schema = self._map_serializer_field(field, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 488, in _map_serializer_field
schema = self._map_serializer_field(field.child_relation, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 516, in _map_serializer_field
schema = self._map_model_field(model_field, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 387, in _map_model_field
assert isinstance(model_field, models.Field)
AssertionError
|
AssertionError
|
def _follow_field_source(model, path: List[str]):
"""
navigate through root model via given navigation path. supports forward/reverse relations.
"""
field_or_property = getattr(model, path[0], None)
if len(path) == 1:
# end of traversal
if isinstance(field_or_property, property):
return field_or_property.fget
elif isinstance(field_or_property, cached_property):
return field_or_property.func
elif callable(field_or_property):
return field_or_property
elif isinstance(field_or_property, ManyToManyDescriptor):
if field_or_property.reverse:
return field_or_property.rel.target_field # m2m reverse
else:
return field_or_property.field.target_field # m2m forward
elif isinstance(field_or_property, ReverseOneToOneDescriptor):
return field_or_property.related.target_field # o2o reverse
elif isinstance(field_or_property, ReverseManyToOneDescriptor):
return field_or_property.rel.target_field # type: ignore # foreign reverse
elif isinstance(field_or_property, ForwardManyToOneDescriptor):
return field_or_property.field.target_field # type: ignore # o2o & foreign forward
else:
field = model._meta.get_field(path[0])
if isinstance(field, ForeignObjectRel):
# case only occurs when relations are traversed in reverse and
# not via the related_name (default: X_set) but the model name.
return field.target_field
else:
return field
else:
if isinstance(field_or_property, property) or callable(field_or_property):
if isinstance(field_or_property, property):
target_model = typing.get_type_hints(field_or_property.fget).get(
"return"
)
else:
target_model = typing.get_type_hints(field_or_property).get("return")
if not target_model:
raise UnableToProceedError(
f'could not follow field source through intermediate property "{path[0]}" '
f"on model {model}. please add a type hint on the model's property/function "
f'to enable traversal of the source path "{".".join(path)}".'
)
return _follow_field_source(target_model, path[1:])
else:
target_model = model._meta.get_field(path[0]).related_model
return _follow_field_source(target_model, path[1:])
|
def _follow_field_source(model, path: List[str]):
"""
navigate through root model via given navigation path. supports forward/reverse relations.
"""
field_or_property = getattr(model, path[0], None)
if len(path) == 1:
# end of traversal
if isinstance(field_or_property, property):
return field_or_property.fget
elif isinstance(field_or_property, cached_property):
return field_or_property.func
elif callable(field_or_property):
return field_or_property
else:
field = model._meta.get_field(path[0])
if isinstance(field, ForeignObjectRel):
# resolve DRF internal object to PK field as approximation
return field.get_related_field() # type: ignore
else:
return field
else:
if isinstance(field_or_property, property) or callable(field_or_property):
if isinstance(field_or_property, property):
target_model = typing.get_type_hints(field_or_property.fget).get(
"return"
)
else:
target_model = typing.get_type_hints(field_or_property).get("return")
if not target_model:
raise UnableToProceedError(
f'could not follow field source through intermediate property "{path[0]}" '
f"on model {model}. please add a type hint on the model's property/function "
f'to enable traversal of the source path "{".".join(path)}".'
)
return _follow_field_source(target_model, path[1:])
else:
target_model = model._meta.get_field(path[0]).related_model
return _follow_field_source(target_model, path[1:])
|
https://github.com/tfranzel/drf-spectacular/issues/323
|
Warning #1: could not resolve field on model <class 'test_spectacular.models.TestModel'> with path "reltd_set". this is likely a custom field that does some unknown magic. maybe consider annotating the field/property? defaulting to "string". (Exception: TestModel has no field named 'reltd_set')
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
main()
File "./manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "test_spectacular/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "test_spectacular/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "test_spectacular/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "test_spectacular/venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/management/commands/spectacular.py", line 50, in handle
schema = generator.get_schema(request=None, public=True)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/generators.py", line 219, in get_schema
paths=self.parse(request, public),
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/generators.py", line 196, in parse
operation = view.schema.get_operation(path, path_regex, method, self.registry)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 83, in get_operation
operation['responses'] = self._get_response_bodies()
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 969, in _get_response_bodies
return {'200': self._get_response_for_code(response_serializers, '200')}
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 1007, in _get_response_for_code
component = self.resolve_serializer(serializer, 'response')
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 1146, in resolve_serializer
component.schema = self._map_serializer(serializer, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 669, in _map_serializer
schema = self._map_basic_serializer(serializer, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 736, in _map_basic_serializer
schema = self._map_serializer_field(field, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 488, in _map_serializer_field
schema = self._map_serializer_field(field.child_relation, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 516, in _map_serializer_field
schema = self._map_model_field(model_field, direction)
File "test_spectacular/venv/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 387, in _map_model_field
assert isinstance(model_field, models.Field)
AssertionError
|
AssertionError
|
def get_schema_operation_parameters(self, auto_schema, *args, **kwargs):
if issubclass(self.target_class, SpectacularDjangoFilterBackendMixin):
warn(
"DEPRECATED - Spectacular's DjangoFilterBackend is superseded by extension. you "
"can simply restore this to the original class, extensions will take care of the "
"rest."
)
model = get_view_model(auto_schema.view)
if not model:
return []
filterset_class = self.target.get_filterset_class(
auto_schema.view, model.objects.none()
)
if not filterset_class:
return []
parameters = []
for field_name, field in filterset_class.base_filters.items():
parameters.append(
build_parameter_type(
name=field_name,
required=field.extra["required"],
location=OpenApiParameter.QUERY,
description=field.label if field.label is not None else field_name,
schema=self.resolve_filter_field(
auto_schema, model, filterset_class, field
),
enum=[c for c, _ in field.extra.get("choices", [])],
)
)
return parameters
|
def get_schema_operation_parameters(self, auto_schema, *args, **kwargs):
if issubclass(self.target_class, SpectacularDjangoFilterBackendMixin):
warn(
"DEPRECATED - Spectacular's DjangoFilterBackend is superseded by extension. you "
"can simply restore this to the original class, extensions will take care of the "
"rest."
)
model = get_view_model(auto_schema.view)
if not model:
return []
filterset_class = self.target.get_filterset_class(
auto_schema.view, model.objects.none()
)
if not filterset_class:
return []
parameters = []
for field_name, field in filterset_class.base_filters.items():
path = field.field_name.split("__")
model_field = follow_field_source(model, path)
parameters.append(
build_parameter_type(
name=field_name,
required=field.extra["required"],
location=OpenApiParameter.QUERY,
description=field.label if field.label is not None else field_name,
schema=auto_schema._map_model_field(model_field, direction=None),
enum=[c for c, _ in field.extra.get("choices", [])],
)
)
return parameters
|
https://github.com/tfranzel/drf-spectacular/issues/252
|
Environment:
Request Method: GET
Request URL: http://localhost:8000/api/schema/
Django Version: 3.1.5
Python Version: 3.8.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'corsheaders',
'rest_framework',
'rest_framework.authtoken',
'taggit',
'taggit_serializer',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'rest_auth',
'rest_auth.registration',
'django_filters',
'private_storage',
'rest_mediabrowser',
'drf_spectacular',
'users',
'content',
'enrollment',
'forum',
'logs',
'billing']
Installed Middleware:
['corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/drf_spectacular/views.py", line 61, in get
return self._get_schema_response(request)
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/drf_spectacular/views.py", line 65, in _get_schema_response
return Response(generator.get_schema(request=request, public=self.serve_public))
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/drf_spectacular/generators.py", line 188, in get_schema
paths=self.parse(request, public),
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/drf_spectacular/generators.py", line 165, in parse
operation = view.schema.get_operation(path, path_regex, method, self.registry)
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 62, in get_operation
parameters = self._get_parameters()
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 186, in _get_parameters
**dict_helper(self._get_filter_parameters()),
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 353, in _get_filter_parameters
parameters += filter_extension.get_schema_operation_parameters(self)
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/drf_spectacular/contrib/django_filters.py", line 42, in get_schema_operation_parameters
schema=auto_schema._map_model_field(model_field, direction=None),
File "/root/.local/share/virtualenvs/server-MrgTHRtU/lib/python3.8/site-packages/drf_spectacular/openapi.py", line 373, in _map_model_field
assert isinstance(model_field, models.Field)
Exception Type: AssertionError at /api/schema/
Exception Value:
|
AssertionError
|
def _map_model_field(self, model_field, direction):
assert isinstance(model_field, models.Field)
# to get a fully initialized serializer field we use DRF's own init logic
try:
field_cls, field_kwargs = serializers.ModelSerializer().build_field(
field_name=model_field.name,
info=get_field_info(model_field.model),
model_class=model_field.model,
nested_depth=0,
)
field = field_cls(**field_kwargs)
except: # noqa
field = None
# For some cases, the DRF init logic either breaks (custom field with internal type) or
# the resulting field is underspecified with regards to the schema (ReadOnlyField).
if field and isinstance(field, serializers.PrimaryKeyRelatedField):
# special case handling only for _resolve_path_parameters() where neither queryset nor
# parent is set by build_field. patch in queryset as _map_serializer_field requires it
if not field.queryset:
field.queryset = model_field.related_model.objects.none()
return self._map_serializer_field(field, direction)
elif field and not anyisinstance(
field, [serializers.ReadOnlyField, serializers.ModelField]
):
return self._map_serializer_field(field, direction)
elif isinstance(model_field, models.ForeignKey):
return self._map_model_field(model_field.target_field, direction)
elif hasattr(models, "JSONField") and isinstance(model_field, models.JSONField):
# fix for DRF==3.11 with django>=3.1 as it is not yet represented in the field_mapping
return build_basic_type(OpenApiTypes.OBJECT)
elif hasattr(models, model_field.get_internal_type()):
# be graceful when the model field is not explicitly mapped to a serializer
internal_type = getattr(models, model_field.get_internal_type())
field_cls = serializers.ModelSerializer.serializer_field_mapping.get(
internal_type
)
if not field_cls:
warn(
f'model field "{model_field.get_internal_type()}" has no mapping in '
f'ModelSerializer. it may be a deprecated field. defaulting to "string"'
)
return build_basic_type(OpenApiTypes.STR)
return self._map_serializer_field(field_cls(), direction)
else:
error(
f'could not resolve model field "{model_field}". failed to resolve through '
f"serializer_field_mapping, get_internal_type(), or any override mechanism. "
f'defaulting to "string"'
)
return build_basic_type(OpenApiTypes.STR)
|
def _map_model_field(self, model_field, direction):
assert isinstance(model_field, models.Field)
# to get a fully initialized serializer field we use DRF's own init logic
try:
field_cls, field_kwargs = serializers.ModelSerializer().build_field(
field_name=model_field.name,
info=get_field_info(model_field.model),
model_class=model_field.model,
nested_depth=0,
)
field = field_cls(**field_kwargs)
except: # noqa
field = None
# For some cases, the DRF init logic either breaks (custom field with internal type) or
# the resulting field is underspecified with regards to the schema (ReadOnlyField).
if field and not anyisinstance(
field, [serializers.ReadOnlyField, serializers.ModelField]
):
return self._map_serializer_field(field, direction)
elif isinstance(model_field, models.ForeignKey):
return self._map_model_field(model_field.target_field, direction)
elif hasattr(models, "JSONField") and isinstance(model_field, models.JSONField):
# fix for DRF==3.11 with django>=3.1 as it is not yet represented in the field_mapping
return build_basic_type(OpenApiTypes.OBJECT)
elif hasattr(models, model_field.get_internal_type()):
# be graceful when the model field is not explicitly mapped to a serializer
internal_type = getattr(models, model_field.get_internal_type())
field_cls = serializers.ModelSerializer.serializer_field_mapping.get(
internal_type
)
if not field_cls:
warn(
f'model field "{model_field.get_internal_type()}" has no mapping in '
f'ModelSerializer. it may be a deprecated field. defaulting to "string"'
)
return build_basic_type(OpenApiTypes.STR)
return self._map_serializer_field(field_cls(), direction)
else:
error(
f'could not resolve model field "{model_field}". failed to resolve through '
f"serializer_field_mapping, get_internal_type(), or any override mechanism. "
f'defaulting to "string"'
)
return build_basic_type(OpenApiTypes.STR)
|
https://github.com/tfranzel/drf-spectacular/issues/258
|
Internal Server Error: /api/schema/
Traceback (most recent call last):
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.9/contextlib.py", line 79, in inner
return func(*args, **kwds)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/views.py", line 61, in get
return self._get_schema_response(request)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/views.py", line 65, in _get_schema_response
return Response(generator.get_schema(request=request, public=self.serve_public))
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/generators.py", line 188, in get_schema
paths=self.parse(request, public),
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/generators.py", line 165, in parse
operation = view.schema.get_operation(path, path_regex, method, self.registry)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/openapi.py", line 62, in get_operation
parameters = self._get_parameters()
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/openapi.py", line 185, in _get_parameters
**dict_helper(self._resolve_path_parameters(path_variables)),
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/openapi.py", line 324, in _resolve_path_parameters
schema = self._map_model_field(model_field, direction=None)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/openapi.py", line 389, in _map_model_field
return self._map_serializer_field(field, direction)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/openapi.py", line 461, in _map_serializer_field
model_field = field.parent.Meta.model._meta.pk
AttributeError: 'NoneType' object has no attribute 'Meta'
|
AttributeError
|
def run(self, evidence, result):
"""Run the sshd_config analysis worker.
Args:
evidence (Evidence object): The evidence we will process.
result (TurbiniaTaskResult): The object to place task results into.
Returns:
TurbiniaTaskResult object.
"""
# Where to store the resulting output file.
output_file_name = "sshd_config_analysis.txt"
output_file_path = os.path.join(self.output_dir, output_file_name)
# Set the output file as the data source for the output evidence.
output_evidence = ReportText(source_path=output_file_path)
# Read the input file
with open(evidence.local_path, "r") as input_file:
sshd_config = input_file.read()
(report, priority, summary) = self.analyse_sshd_config(sshd_config)
output_evidence.text_data = report
result.report_priority = priority
result.report_data = report
# Write the report to the output file.
with open(output_file_path, "wb") as fh:
fh.write(output_evidence.text_data.encode("utf-8"))
# Add the resulting evidence to the result object.
result.add_evidence(output_evidence, evidence.config)
result.close(self, success=True, status=summary)
return result
|
def run(self, evidence, result):
"""Run the sshd_config analysis worker.
Args:
evidence (Evidence object): The evidence we will process.
result (TurbiniaTaskResult): The object to place task results into.
Returns:
TurbiniaTaskResult object.
"""
# Where to store the resulting output file.
output_file_name = "sshd_config_analysis.txt"
output_file_path = os.path.join(self.output_dir, output_file_name)
# Set the output file as the data source for the output evidence.
output_evidence = ReportText(source_path=output_file_path)
# Read the input file
with open(evidence.local_path, "r") as input_file:
sshd_config = input_file.read()
(report, priority, summary) = self.analyse_sshd_config(sshd_config)
output_evidence.text_data = report
result.report_priority = priority
result.report_data = report
# Write the report to the output file.
with open(output_file_path, "w") as fh:
fh.write(output_evidence.text_data.encode("utf-8"))
# Add the resulting evidence to the result object.
result.add_evidence(output_evidence, evidence.config)
result.close(self, success=True, status=summary)
return result
|
https://github.com/google/turbinia/issues/522
|
Traceback (most recent call last):
File "/turbinia/turbinia/workers/__init__.py", line 719, in run_wrapper
self.result = self.run(evidence, self.result)
File "/turbinia/turbinia/workers/sshd.py", line 58, in run
fh.write(output_evidence.text_data.encode('utf-8'))
TypeError: write() argument must be str, not bytes
|
TypeError
|
def format_record(self, frame, file, lnum, func, lines, index):
"""Format a single stack frame"""
Colors = self.Colors # just a shorthand + quicker name lookup
ColorsNormal = Colors.Normal # used a lot
col_scheme = self.color_scheme_table.active_scheme_name
indent = " " * INDENT_SIZE
em_normal = "%s\n%s%s" % (Colors.valEm, indent, ColorsNormal)
undefined = "%sundefined%s" % (Colors.em, ColorsNormal)
tpl_link = "%s%%s%s" % (Colors.filenameEm, ColorsNormal)
tpl_call = "in %s%%s%s%%s%s" % (Colors.vName, Colors.valEm, ColorsNormal)
tpl_call_fail = "in %s%%s%s(***failed resolving arguments***)%s" % (
Colors.vName,
Colors.valEm,
ColorsNormal,
)
tpl_local_var = "%s%%s%s" % (Colors.vName, ColorsNormal)
tpl_global_var = "%sglobal%s %s%%s%s" % (
Colors.em,
ColorsNormal,
Colors.vName,
ColorsNormal,
)
tpl_name_val = "%%s %s= %%s%s" % (Colors.valEm, ColorsNormal)
tpl_line = "%s%%s%s %%s" % (Colors.lineno, ColorsNormal)
tpl_line_em = "%s%%s%s %%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal)
abspath = os.path.abspath
if not file:
file = "?"
elif file.startswith(str("<")) and file.endswith(str(">")):
# Not a real filename, no problem...
pass
elif not os.path.isabs(file):
# Try to make the filename absolute by trying all
# sys.path entries (which is also what linecache does)
for dirname in sys.path:
try:
fullname = os.path.join(dirname, file)
if os.path.isfile(fullname):
file = os.path.abspath(fullname)
break
except Exception:
# Just in case that sys.path contains very
# strange entries...
pass
file = py3compat.cast_unicode(file, util_path.fs_encoding)
link = tpl_link % util_path.compress_user(file)
args, varargs, varkw, locals = inspect.getargvalues(frame)
if func == "?":
call = ""
else:
# Decide whether to include variable details or not
var_repr = self.include_vars and eqrepr or nullrepr
try:
call = tpl_call % (
func,
inspect.formatargvalues(
args, varargs, varkw, locals, formatvalue=var_repr
),
)
except KeyError:
# This happens in situations like errors inside generator
# expressions, where local variables are listed in the
# line, but can't be extracted from the frame. I'm not
# 100% sure this isn't actually a bug in inspect itself,
# but since there's no info for us to compute with, the
# best we can do is report the failure and move on. Here
# we must *not* call any traceback construction again,
# because that would mess up use of %debug later on. So we
# simply report the failure and move on. The only
# limitation will be that this frame won't have locals
# listed in the call signature. Quite subtle problem...
# I can't think of a good way to validate this in a unit
# test, but running a script consisting of:
# dict( (k,v.strip()) for (k,v) in range(10) )
# will illustrate the error, if this exception catch is
# disabled.
call = tpl_call_fail % func
# Don't attempt to tokenize binary files.
if file.endswith((".so", ".pyd", ".dll")):
return "%s %s\n" % (link, call)
elif file.endswith((".pyc", ".pyo")):
# Look up the corresponding source file.
try:
file = openpy.source_from_cache(file)
except ValueError:
# Failed to get the source file for some reason
# E.g. https://github.com/ipython/ipython/issues/9486
return "%s %s\n" % (link, call)
def linereader(file=file, lnum=[lnum], getline=linecache.getline):
line = getline(file, lnum[0])
lnum[0] += 1
return line
# Build the list of names on this line of code where the exception
# occurred.
try:
names = []
name_cont = False
for token_type, token, start, end, line in generate_tokens(linereader):
# build composite names
if token_type == tokenize.NAME and token not in keyword.kwlist:
if name_cont:
# Continuation of a dotted name
try:
names[-1].append(token)
except IndexError:
names.append([token])
name_cont = False
else:
# Regular new names. We append everything, the caller
# will be responsible for pruning the list later. It's
# very tricky to try to prune as we go, b/c composite
# names can fool us. The pruning at the end is easy
# to do (or the caller can print a list with repeated
# names if so desired.
names.append([token])
elif token == ".":
name_cont = True
elif token_type == tokenize.NEWLINE:
break
except (IndexError, UnicodeDecodeError, SyntaxError):
# signals exit of tokenizer
# SyntaxError can occur if the file is not actually Python
# - see gh-6300
pass
except tokenize.TokenError as msg:
# Tokenizing may fail for various reasons, many of which are
# harmless. (A good example is when the line in question is the
# close of a triple-quoted string, cf gh-6864). We don't want to
# show this to users, but want make it available for debugging
# purposes.
_m = (
"An unexpected error occurred while tokenizing input\n"
"The following traceback may be corrupted or invalid\n"
"The error message is: %s\n" % msg
)
debug(_m)
# Join composite names (e.g. "dict.fromkeys")
names = [".".join(n) for n in names]
# prune names list of duplicates, but keep the right order
unique_names = uniq_stable(names)
# Start loop over vars
lvals = []
if self.include_vars:
for name_full in unique_names:
name_base = name_full.split(".", 1)[0]
if name_base in frame.f_code.co_varnames:
if name_base in locals:
try:
value = repr(eval(name_full, locals))
except:
value = undefined
else:
value = undefined
name = tpl_local_var % name_full
else:
if name_base in frame.f_globals:
try:
value = repr(eval(name_full, frame.f_globals))
except:
value = undefined
else:
value = undefined
name = tpl_global_var % name_full
lvals.append(tpl_name_val % (name, value))
if lvals:
lvals = "%s%s" % (indent, em_normal.join(lvals))
else:
lvals = ""
level = "%s %s\n" % (link, call)
if index is None:
return level
else:
_line_format = PyColorize.Parser(style=col_scheme, parent=self).format2
return "%s%s" % (
level,
"".join(
_format_traceback_lines(lnum, index, lines, Colors, lvals, _line_format)
),
)
|
def format_record(self, frame, file, lnum, func, lines, index):
"""Format a single stack frame"""
Colors = self.Colors # just a shorthand + quicker name lookup
ColorsNormal = Colors.Normal # used a lot
col_scheme = self.color_scheme_table.active_scheme_name
indent = " " * INDENT_SIZE
em_normal = "%s\n%s%s" % (Colors.valEm, indent, ColorsNormal)
undefined = "%sundefined%s" % (Colors.em, ColorsNormal)
tpl_link = "%s%%s%s" % (Colors.filenameEm, ColorsNormal)
tpl_call = "in %s%%s%s%%s%s" % (Colors.vName, Colors.valEm, ColorsNormal)
tpl_call_fail = "in %s%%s%s(***failed resolving arguments***)%s" % (
Colors.vName,
Colors.valEm,
ColorsNormal,
)
tpl_local_var = "%s%%s%s" % (Colors.vName, ColorsNormal)
tpl_global_var = "%sglobal%s %s%%s%s" % (
Colors.em,
ColorsNormal,
Colors.vName,
ColorsNormal,
)
tpl_name_val = "%%s %s= %%s%s" % (Colors.valEm, ColorsNormal)
tpl_line = "%s%%s%s %%s" % (Colors.lineno, ColorsNormal)
tpl_line_em = "%s%%s%s %%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal)
abspath = os.path.abspath
if not file:
file = "?"
elif file.startswith(str("<")) and file.endswith(str(">")):
# Not a real filename, no problem...
pass
elif not os.path.isabs(file):
# Try to make the filename absolute by trying all
# sys.path entries (which is also what linecache does)
for dirname in sys.path:
try:
fullname = os.path.join(dirname, file)
if os.path.isfile(fullname):
file = os.path.abspath(fullname)
break
except Exception:
# Just in case that sys.path contains very
# strange entries...
pass
file = py3compat.cast_unicode(file, util_path.fs_encoding)
link = tpl_link % util_path.compress_user(file)
args, varargs, varkw, locals = inspect.getargvalues(frame)
if func == "?":
call = ""
else:
# Decide whether to include variable details or not
var_repr = self.include_vars and eqrepr or nullrepr
try:
call = tpl_call % (
func,
inspect.formatargvalues(
args, varargs, varkw, locals, formatvalue=var_repr
),
)
except KeyError:
# This happens in situations like errors inside generator
# expressions, where local variables are listed in the
# line, but can't be extracted from the frame. I'm not
# 100% sure this isn't actually a bug in inspect itself,
# but since there's no info for us to compute with, the
# best we can do is report the failure and move on. Here
# we must *not* call any traceback construction again,
# because that would mess up use of %debug later on. So we
# simply report the failure and move on. The only
# limitation will be that this frame won't have locals
# listed in the call signature. Quite subtle problem...
# I can't think of a good way to validate this in a unit
# test, but running a script consisting of:
# dict( (k,v.strip()) for (k,v) in range(10) )
# will illustrate the error, if this exception catch is
# disabled.
call = tpl_call_fail % func
# Don't attempt to tokenize binary files.
if file.endswith((".so", ".pyd", ".dll")):
return "%s %s\n" % (link, call)
elif file.endswith((".pyc", ".pyo")):
# Look up the corresponding source file.
try:
file = openpy.source_from_cache(file)
except ValueError:
# Failed to get the source file for some reason
# E.g. https://github.com/ipython/ipython/issues/9486
return "%s %s\n" % (link, call)
def linereader(file=file, lnum=[lnum], getline=linecache.getline):
line = getline(file, lnum[0])
lnum[0] += 1
return line
# Build the list of names on this line of code where the exception
# occurred.
try:
names = []
name_cont = False
for token_type, token, start, end, line in generate_tokens(linereader):
# build composite names
if token_type == tokenize.NAME and token not in keyword.kwlist:
if name_cont:
# Continuation of a dotted name
try:
names[-1].append(token)
except IndexError:
names.append([token])
name_cont = False
else:
# Regular new names. We append everything, the caller
# will be responsible for pruning the list later. It's
# very tricky to try to prune as we go, b/c composite
# names can fool us. The pruning at the end is easy
# to do (or the caller can print a list with repeated
# names if so desired.
names.append([token])
elif token == ".":
name_cont = True
elif token_type == tokenize.NEWLINE:
break
except (IndexError, UnicodeDecodeError, SyntaxError):
# signals exit of tokenizer
# SyntaxError can occur if the file is not actually Python
# - see gh-6300
pass
except tokenize.TokenError as msg:
_m = (
"An unexpected error occurred while tokenizing input\n"
"The following traceback may be corrupted or invalid\n"
"The error message is: %s\n" % msg
)
error(_m)
# Join composite names (e.g. "dict.fromkeys")
names = [".".join(n) for n in names]
# prune names list of duplicates, but keep the right order
unique_names = uniq_stable(names)
# Start loop over vars
lvals = []
if self.include_vars:
for name_full in unique_names:
name_base = name_full.split(".", 1)[0]
if name_base in frame.f_code.co_varnames:
if name_base in locals:
try:
value = repr(eval(name_full, locals))
except:
value = undefined
else:
value = undefined
name = tpl_local_var % name_full
else:
if name_base in frame.f_globals:
try:
value = repr(eval(name_full, frame.f_globals))
except:
value = undefined
else:
value = undefined
name = tpl_global_var % name_full
lvals.append(tpl_name_val % (name, value))
if lvals:
lvals = "%s%s" % (indent, em_normal.join(lvals))
else:
lvals = ""
level = "%s %s\n" % (link, call)
if index is None:
return level
else:
_line_format = PyColorize.Parser(style=col_scheme, parent=self).format2
return "%s%s" % (
level,
"".join(
_format_traceback_lines(lnum, index, lines, Colors, lvals, _line_format)
),
)
|
https://github.com/ipython/ipython/issues/6864
|
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line string', (1, 0))
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-15-8d28bd905cfc> in <module>()
1 raise Exception(r'''foo
----> 2 ''')
Exception: foo
|
Exception
|
def _run_with_debugger(self, code, code_ns, filename=None, bp_line=None, bp_file=None):
"""
Run `code` in debugger with a break point.
Parameters
----------
code : str
Code to execute.
code_ns : dict
A namespace in which `code` is executed.
filename : str
`code` is ran as if it is in `filename`.
bp_line : int, optional
Line number of the break point.
bp_file : str, optional
Path to the file in which break point is specified.
`filename` is used if not given.
Raises
------
UsageError
If the break point given by `bp_line` is not valid.
"""
deb = self.shell.InteractiveTB.pdb
if not deb:
self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
deb = self.shell.InteractiveTB.pdb
# deb.checkline() fails if deb.curframe exists but is None; it can
# handle it not existing. https://github.com/ipython/ipython/issues/10028
if hasattr(deb, "curframe"):
del deb.curframe
# reset Breakpoint state, which is moronically kept
# in a class
bdb.Breakpoint.next = 1
bdb.Breakpoint.bplist = {}
bdb.Breakpoint.bpbynumber = [None]
if bp_line is not None:
# Set an initial breakpoint to stop execution
maxtries = 10
bp_file = bp_file or filename
checkline = deb.checkline(bp_file, bp_line)
if not checkline:
for bp in range(bp_line + 1, bp_line + maxtries + 1):
if deb.checkline(bp_file, bp):
break
else:
msg = (
"\nI failed to find a valid line to set "
"a breakpoint\n"
"after trying up to line: %s.\n"
"Please set a valid breakpoint manually "
"with the -b option." % bp
)
raise UsageError(msg)
# if we find a good linenumber, set the breakpoint
deb.do_break("%s:%s" % (bp_file, bp_line))
if filename:
# Mimic Pdb._runscript(...)
deb._wait_for_mainpyfile = True
deb.mainpyfile = deb.canonic(filename)
# Start file run
print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
try:
if filename:
# save filename so it can be used by methods on the deb object
deb._exec_filename = filename
while True:
try:
deb.run(code, code_ns)
except Restart:
print("Restarting")
if filename:
deb._wait_for_mainpyfile = True
deb.mainpyfile = deb.canonic(filename)
continue
else:
break
except:
etype, value, tb = sys.exc_info()
# Skip three frames in the traceback: the %run one,
# one inside bdb.py, and the command-line typed by the
# user (run by exec in pdb itself).
self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
|
def _run_with_debugger(self, code, code_ns, filename=None, bp_line=None, bp_file=None):
"""
Run `code` in debugger with a break point.
Parameters
----------
code : str
Code to execute.
code_ns : dict
A namespace in which `code` is executed.
filename : str
`code` is ran as if it is in `filename`.
bp_line : int, optional
Line number of the break point.
bp_file : str, optional
Path to the file in which break point is specified.
`filename` is used if not given.
Raises
------
UsageError
If the break point given by `bp_line` is not valid.
"""
deb = self.shell.InteractiveTB.pdb
if not deb:
self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
deb = self.shell.InteractiveTB.pdb
# reset Breakpoint state, which is moronically kept
# in a class
bdb.Breakpoint.next = 1
bdb.Breakpoint.bplist = {}
bdb.Breakpoint.bpbynumber = [None]
if bp_line is not None:
# Set an initial breakpoint to stop execution
maxtries = 10
bp_file = bp_file or filename
checkline = deb.checkline(bp_file, bp_line)
if not checkline:
for bp in range(bp_line + 1, bp_line + maxtries + 1):
if deb.checkline(bp_file, bp):
break
else:
msg = (
"\nI failed to find a valid line to set "
"a breakpoint\n"
"after trying up to line: %s.\n"
"Please set a valid breakpoint manually "
"with the -b option." % bp
)
raise UsageError(msg)
# if we find a good linenumber, set the breakpoint
deb.do_break("%s:%s" % (bp_file, bp_line))
if filename:
# Mimic Pdb._runscript(...)
deb._wait_for_mainpyfile = True
deb.mainpyfile = deb.canonic(filename)
# Start file run
print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
try:
if filename:
# save filename so it can be used by methods on the deb object
deb._exec_filename = filename
while True:
try:
deb.run(code, code_ns)
except Restart:
print("Restarting")
if filename:
deb._wait_for_mainpyfile = True
deb.mainpyfile = deb.canonic(filename)
continue
else:
break
except:
etype, value, tb = sys.exc_info()
# Skip three frames in the traceback: the %run one,
# one inside bdb.py, and the command-line typed by the
# user (run by exec in pdb itself).
self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
|
https://github.com/ipython/ipython/issues/10028
|
~/Workspace/puzzles/FiveThirtyEightRiddler $ ipython
Python 3.4.2 (default, Jun 20 2016, 14:25:19)
Type "copyright", "credits" or "license" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: %run -d test.py
Breakpoint 1 at /home/andrew/Workspace/puzzles/FiveThirtyEightRiddler/test.py:1
NOTE: Enter 'c' at the ipdb> prompt to continue execution.
/home/andrew/Workspace/puzzles/FiveThirtyEightRiddler/test.py(1)<module>()
1---> 1 print('test')
ipdb> c
test
In [2]: %run -d test.py
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-63fffe36c4af> in <module>()
----> 1 get_ipython().magic('run -d test.py')
/usr/lib/python3.4/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
2156 magic_name, _, magic_arg_s = arg_s.partition(' ')
2157 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2158 return self.run_line_magic(magic_name, magic_arg_s)
2159
2160 #-------------------------------------------------------------------------
/usr/lib/python3.4/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
2077 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2078 with self.builtin_trap:
-> 2079 result = fn(*args,**kwargs)
2080 return result
2081
<decorator-gen-57> in run(self, parameter_s, runner, file_finder)
/usr/lib/python3.4/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
186 # but it's overkill for just that one bit of state.
187 def magic_deco(arg):
--> 188 call = lambda f, *a, **k: f(*a, **k)
189
190 if callable(arg):
/usr/lib/python3.4/site-packages/IPython/core/magics/execution.py in run(self, parameter_s, runner, file_finder)
713 opts.get('b', ['1'])[0], filename)
714 self._run_with_debugger(
--> 715 code, code_ns, filename, bp_line, bp_file)
716 else:
717 if 'm' in opts:
/usr/lib/python3.4/site-packages/IPython/core/magics/execution.py in _run_with_debugger(self, code, code_ns, filename, bp_line, bp_file)
816 maxtries = 10
817 bp_file = bp_file or filename
--> 818 checkline = deb.checkline(bp_file, bp_line)
819 if not checkline:
820 for bp in range(bp_line + 1, bp_line + maxtries + 1):
/usr/lib64/python3.4/pdb.py in checkline(self, filename, lineno)
743 # this method should be callable before starting debugging, so default
744 # to "no globals" if there is no current frame
--> 745 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
746 line = linecache.getline(filename, lineno, globs)
747 if not line:
AttributeError: 'NoneType' object has no attribute 'f_globals'
In [3]:
|
AttributeError
|
def reload(
module, exclude=("sys", "os.path", builtin_mod_name, "__main__", "numpy._globals")
):
"""Recursively reload all modules used in the given module. Optionally
takes a list of modules to exclude from reloading. The default exclude
list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
display, exception, and io hooks.
"""
global found_now
for i in exclude:
found_now[i] = 1
try:
with replace_import_hook(deep_import_hook):
return deep_reload_hook(module)
finally:
found_now = {}
|
def reload(module, exclude=("sys", "os.path", builtin_mod_name, "__main__")):
"""Recursively reload all modules used in the given module. Optionally
takes a list of modules to exclude from reloading. The default exclude
list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
display, exception, and io hooks.
"""
global found_now
for i in exclude:
found_now[i] = 1
try:
with replace_import_hook(deep_import_hook):
return deep_reload_hook(module)
finally:
found_now = {}
|
https://github.com/ipython/ipython/issues/9983
|
======================================================================
ERROR: Test that NumPy can be deep reloaded.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/site-packages/nose/case.py", line 198, in runTest
self.test(*self.arg)
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/site-packages/IPython/testing/decorators.py", line 212, in skipper_func
return f(*args, **kwargs)
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/site-packages/IPython/lib/tests/test_deepreload.py", line 38, in test_deepreload_numpy
dreload(numpy, exclude=exclude)
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/site-packages/IPython/lib/deepreload.py", line 341, in reload
return deep_reload_hook(module)
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/site-packages/IPython/lib/deepreload.py", line 311, in deep_reload_hook
newm = imp.load_module(name, fp, filename, stuff)
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/imp.py", line 245, in load_module
return load_package(name, filename)
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/imp.py", line 215, in load_package
return methods.exec(sys.modules[name])
File "<frozen importlib._bootstrap>", line 1153, in exec
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/site-packages/numpy/__init__.py", line 112, in <module>
from ._globals import ModuleDeprecationWarning, VisibleDeprecationWarning
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/site-packages/IPython/lib/deepreload.py", line 252, in deep_import_hook
head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/site-packages/IPython/lib/deepreload.py", line 156, in load_next
result = import_submodule(mod, subname, buf)
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/site-packages/IPython/lib/deepreload.py", line 201, in import_submodule
m = imp.load_module(fullname, fp, filename, stuff)
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/imp.py", line 235, in load_module
return load_source(name, filename, file)
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/imp.py", line 169, in load_source
module = methods.exec(sys.modules[name])
File "<frozen importlib._bootstrap>", line 1153, in exec
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "/var/lib/jenkins/shiningpanda/jobs/65e9266d/virtualenvs/d41d8cd9/lib/python3.4/site-packages/numpy/_globals.py", line 29, in <module>
raise RuntimeError('Reloading numpy._globals is not allowed')
nose.proxy.RuntimeError: Reloading numpy._globals is not allowed
|
nose.proxy.RuntimeError
|
def global_matches(self, text):
"""Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace or self.global_namespace that match.
"""
# print 'Completer->global_matches, txt=%r' % text # dbg
matches = []
match_append = matches.append
n = len(text)
for lst in [
keyword.kwlist,
builtin_mod.__dict__.keys(),
self.namespace.keys(),
self.global_namespace.keys(),
]:
for word in lst:
if word[:n] == text and word != "__builtins__":
match_append(word)
return [cast_unicode_py2(m) for m in matches]
|
def global_matches(self, text):
"""Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace or self.global_namespace that match.
"""
# print 'Completer->global_matches, txt=%r' % text # dbg
matches = []
match_append = matches.append
n = len(text)
for lst in [
keyword.kwlist,
builtin_mod.__dict__.keys(),
self.namespace.keys(),
self.global_namespace.keys(),
]:
for word in lst:
if word[:n] == text and word != "__builtins__":
match_append(word)
return matches
|
https://github.com/ipython/ipython/issues/9379
|
Python 2.7.11+ (default, Mar 30 2016, 21:00:42)
Type "copyright", "credits" or "license" for more information.
IPython 5.0.0.dev -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: dException in thread Thread-7:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/interface.py", line 742, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/home/bwillar0/projects/python/ipython/IPython/terminal/ptshell.py", line 55, in gets
m = unicodedata.normalize('NFC', m)
TypeError: normalize() argument 2 must be unicode, not str
|
TypeError
|
def attr_matches(self, text):
"""Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluatable in self.namespace or self.global_namespace, it will be
evaluated and its attributes (as revealed by dir()) are used as
possible completions. (For class instances, class members are are
also considered.)
WARNING: this can still invoke arbitrary C code, if an object
with a __getattr__ hook is evaluated.
"""
# io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
# Another option, seems to work great. Catches things like ''.<tab>
m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
if m:
expr, attr = m.group(1, 3)
elif self.greedy:
m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
if not m2:
return []
expr, attr = m2.group(1, 2)
else:
return []
try:
obj = eval(expr, self.namespace)
except:
try:
obj = eval(expr, self.global_namespace)
except:
return []
if self.limit_to__all__ and hasattr(obj, "__all__"):
words = get__all__entries(obj)
else:
words = dir2(obj)
try:
words = generics.complete_object(obj, words)
except TryNext:
pass
except Exception:
# Silence errors from completion function
# raise # dbg
pass
# Build match list to return
n = len(attr)
return ["%s.%s" % (expr, w) for w in words if w[:n] == attr]
|
def attr_matches(self, text):
"""Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluatable in self.namespace or self.global_namespace, it will be
evaluated and its attributes (as revealed by dir()) are used as
possible completions. (For class instances, class members are are
also considered.)
WARNING: this can still invoke arbitrary C code, if an object
with a __getattr__ hook is evaluated.
"""
# io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
# Another option, seems to work great. Catches things like ''.<tab>
m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
if m:
expr, attr = m.group(1, 3)
elif self.greedy:
m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
if not m2:
return []
expr, attr = m2.group(1, 2)
else:
return []
try:
obj = eval(expr, self.namespace)
except:
try:
obj = eval(expr, self.global_namespace)
except:
return []
if self.limit_to__all__ and hasattr(obj, "__all__"):
words = get__all__entries(obj)
else:
words = dir2(obj)
try:
words = generics.complete_object(obj, words)
except TryNext:
pass
except Exception:
# Silence errors from completion function
# raise # dbg
pass
# Build match list to return
n = len(attr)
res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr]
return res
|
https://github.com/ipython/ipython/issues/9379
|
Python 2.7.11+ (default, Mar 30 2016, 21:00:42)
Type "copyright", "credits" or "license" for more information.
IPython 5.0.0.dev -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: dException in thread Thread-7:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/interface.py", line 742, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/home/bwillar0/projects/python/ipython/IPython/terminal/ptshell.py", line 55, in gets
m = unicodedata.normalize('NFC', m)
TypeError: normalize() argument 2 must be unicode, not str
|
TypeError
|
def get__all__entries(obj):
"""returns the strings in the __all__ attribute"""
try:
words = getattr(obj, "__all__")
except:
return []
return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
|
def get__all__entries(obj):
"""returns the strings in the __all__ attribute"""
try:
words = getattr(obj, "__all__")
except:
return []
return [w for w in words if isinstance(w, string_types)]
|
https://github.com/ipython/ipython/issues/9379
|
Python 2.7.11+ (default, Mar 30 2016, 21:00:42)
Type "copyright", "credits" or "license" for more information.
IPython 5.0.0.dev -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: dException in thread Thread-7:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/interface.py", line 742, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/home/bwillar0/projects/python/ipython/IPython/terminal/ptshell.py", line 55, in gets
m = unicodedata.normalize('NFC', m)
TypeError: normalize() argument 2 must be unicode, not str
|
TypeError
|
def file_matches(self, text):
"""Match filenames, expanding ~USER type strings.
Most of the seemingly convoluted logic in this completer is an
attempt to handle filenames with spaces in them. And yet it's not
quite perfect, because Python's readline doesn't expose all of the
GNU readline details needed for this to be done correctly.
For a filename with a space in it, the printed completions will be
only the parts after what's already been typed (instead of the
full completions, as is normally done). I don't think with the
current (as of Python 2.3) Python readline it's possible to do
better."""
# io.rprint('Completer->file_matches: <%r>' % text) # dbg
# chars that require escaping with backslash - i.e. chars
# that readline treats incorrectly as delimiters, but we
# don't want to treat as delimiters in filename matching
# when escaped with backslash
if text.startswith("!"):
text = text[1:]
text_prefix = "!"
else:
text_prefix = ""
text_until_cursor = self.text_until_cursor
# track strings with open quotes
open_quotes = has_open_quotes(text_until_cursor)
if "(" in text_until_cursor or "[" in text_until_cursor:
lsplit = text
else:
try:
# arg_split ~ shlex.split, but with unicode bugs fixed by us
lsplit = arg_split(text_until_cursor)[-1]
except ValueError:
# typically an unmatched ", or backslash without escaped char.
if open_quotes:
lsplit = text_until_cursor.split(open_quotes)[-1]
else:
return []
except IndexError:
# tab pressed on empty line
lsplit = ""
if not open_quotes and lsplit != protect_filename(lsplit):
# if protectables are found, do matching on the whole escaped name
has_protectables = True
text0, text = text, lsplit
else:
has_protectables = False
text = os.path.expanduser(text)
if text == "":
return [
text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")
]
# Compute the matches from the filesystem
m0 = self.clean_glob(text.replace("\\", ""))
if has_protectables:
# If we had protectables, we need to revert our changes to the
# beginning of filename so that we don't double-write the part
# of the filename we have so far
len_lsplit = len(lsplit)
matches = [text_prefix + text0 + protect_filename(f[len_lsplit:]) for f in m0]
else:
if open_quotes:
# if we have a string with an open quote, we don't need to
# protect the names at all (and we _shouldn't_, as it
# would cause bugs when the filesystem call is made).
matches = m0
else:
matches = [text_prefix + protect_filename(f) for f in m0]
# Mark directories in input list by appending '/' to their names.
return [cast_unicode_py2(x + "/") if os.path.isdir(x) else x for x in matches]
|
def file_matches(self, text):
"""Match filenames, expanding ~USER type strings.
Most of the seemingly convoluted logic in this completer is an
attempt to handle filenames with spaces in them. And yet it's not
quite perfect, because Python's readline doesn't expose all of the
GNU readline details needed for this to be done correctly.
For a filename with a space in it, the printed completions will be
only the parts after what's already been typed (instead of the
full completions, as is normally done). I don't think with the
current (as of Python 2.3) Python readline it's possible to do
better."""
# io.rprint('Completer->file_matches: <%r>' % text) # dbg
# chars that require escaping with backslash - i.e. chars
# that readline treats incorrectly as delimiters, but we
# don't want to treat as delimiters in filename matching
# when escaped with backslash
if text.startswith("!"):
text = text[1:]
text_prefix = "!"
else:
text_prefix = ""
text_until_cursor = self.text_until_cursor
# track strings with open quotes
open_quotes = has_open_quotes(text_until_cursor)
if "(" in text_until_cursor or "[" in text_until_cursor:
lsplit = text
else:
try:
# arg_split ~ shlex.split, but with unicode bugs fixed by us
lsplit = arg_split(text_until_cursor)[-1]
except ValueError:
# typically an unmatched ", or backslash without escaped char.
if open_quotes:
lsplit = text_until_cursor.split(open_quotes)[-1]
else:
return []
except IndexError:
# tab pressed on empty line
lsplit = ""
if not open_quotes and lsplit != protect_filename(lsplit):
# if protectables are found, do matching on the whole escaped name
has_protectables = True
text0, text = text, lsplit
else:
has_protectables = False
text = os.path.expanduser(text)
if text == "":
return [text_prefix + protect_filename(f) for f in self.glob("*")]
# Compute the matches from the filesystem
m0 = self.clean_glob(text.replace("\\", ""))
if has_protectables:
# If we had protectables, we need to revert our changes to the
# beginning of filename so that we don't double-write the part
# of the filename we have so far
len_lsplit = len(lsplit)
matches = [text_prefix + text0 + protect_filename(f[len_lsplit:]) for f in m0]
else:
if open_quotes:
# if we have a string with an open quote, we don't need to
# protect the names at all (and we _shouldn't_, as it
# would cause bugs when the filesystem call is made).
matches = m0
else:
matches = [text_prefix + protect_filename(f) for f in m0]
# io.rprint('mm', matches) # dbg
# Mark directories in input list by appending '/' to their names.
matches = [x + "/" if os.path.isdir(x) else x for x in matches]
return matches
|
https://github.com/ipython/ipython/issues/9379
|
Python 2.7.11+ (default, Mar 30 2016, 21:00:42)
Type "copyright", "credits" or "license" for more information.
IPython 5.0.0.dev -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: dException in thread Thread-7:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/interface.py", line 742, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/home/bwillar0/projects/python/ipython/IPython/terminal/ptshell.py", line 55, in gets
m = unicodedata.normalize('NFC', m)
TypeError: normalize() argument 2 must be unicode, not str
|
TypeError
|
def magic_matches(self, text):
"""Match magics"""
# print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
# Get all shell magics now rather than statically, so magics loaded at
# runtime show up too.
lsm = self.shell.magics_manager.lsmagic()
line_magics = lsm["line"]
cell_magics = lsm["cell"]
pre = self.magic_escape
pre2 = pre + pre
# Completion logic:
# - user gives %%: only do cell magics
# - user gives %: do both line and cell magics
# - no prefix: do both
# In other words, line magics are skipped if the user gives %% explicitly
bare_text = text.lstrip(pre)
comp = [pre2 + m for m in cell_magics if m.startswith(bare_text)]
if not text.startswith(pre2):
comp += [pre + m for m in line_magics if m.startswith(bare_text)]
return [cast_unicode_py2(c) for c in comp]
|
def magic_matches(self, text):
"""Match magics"""
# print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
# Get all shell magics now rather than statically, so magics loaded at
# runtime show up too.
lsm = self.shell.magics_manager.lsmagic()
line_magics = lsm["line"]
cell_magics = lsm["cell"]
pre = self.magic_escape
pre2 = pre + pre
# Completion logic:
# - user gives %%: only do cell magics
# - user gives %: do both line and cell magics
# - no prefix: do both
# In other words, line magics are skipped if the user gives %% explicitly
bare_text = text.lstrip(pre)
comp = [pre2 + m for m in cell_magics if m.startswith(bare_text)]
if not text.startswith(pre2):
comp += [pre + m for m in line_magics if m.startswith(bare_text)]
return comp
|
https://github.com/ipython/ipython/issues/9379
|
Python 2.7.11+ (default, Mar 30 2016, 21:00:42)
Type "copyright", "credits" or "license" for more information.
IPython 5.0.0.dev -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: dException in thread Thread-7:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/interface.py", line 742, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/home/bwillar0/projects/python/ipython/IPython/terminal/ptshell.py", line 55, in gets
m = unicodedata.normalize('NFC', m)
TypeError: normalize() argument 2 must be unicode, not str
|
TypeError
|
def python_func_kw_matches(self, text):
"""Match named parameters (kwargs) of the last open function"""
if "." in text: # a parameter cannot be dotted
return []
try:
regexp = self.__funcParamsRegex
except AttributeError:
regexp = self.__funcParamsRegex = re.compile(
r"""
'.*?(?<!\\)' | # single quoted strings or
".*?(?<!\\)" | # double quoted strings or
\w+ | # identifier
\S # other characters
""",
re.VERBOSE | re.DOTALL,
)
# 1. find the nearest identifier that comes before an unclosed
# parenthesis before the cursor
# e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
tokens = regexp.findall(self.text_until_cursor)
tokens.reverse()
iterTokens = iter(tokens)
openPar = 0
for token in iterTokens:
if token == ")":
openPar -= 1
elif token == "(":
openPar += 1
if openPar > 0:
# found the last unclosed parenthesis
break
else:
return []
# 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
ids = []
isId = re.compile(r"\w+$").match
while True:
try:
ids.append(next(iterTokens))
if not isId(ids[-1]):
ids.pop()
break
if not next(iterTokens) == ".":
break
except StopIteration:
break
# lookup the candidate callable matches either using global_matches
# or attr_matches for dotted names
if len(ids) == 1:
callableMatches = self.global_matches(ids[0])
else:
callableMatches = self.attr_matches(".".join(ids[::-1]))
argMatches = []
for callableMatch in callableMatches:
try:
namedArgs = self._default_arguments(eval(callableMatch, self.namespace))
except:
continue
for namedArg in namedArgs:
if namedArg.startswith(text):
argMatches.append("%s=" % namedArg)
return argMatches
|
def python_func_kw_matches(self, text):
"""Match named parameters (kwargs) of the last open function"""
if "." in text: # a parameter cannot be dotted
return []
try:
regexp = self.__funcParamsRegex
except AttributeError:
regexp = self.__funcParamsRegex = re.compile(
r"""
'.*?(?<!\\)' | # single quoted strings or
".*?(?<!\\)" | # double quoted strings or
\w+ | # identifier
\S # other characters
""",
re.VERBOSE | re.DOTALL,
)
# 1. find the nearest identifier that comes before an unclosed
# parenthesis before the cursor
# e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
tokens = regexp.findall(self.text_until_cursor)
tokens.reverse()
iterTokens = iter(tokens)
openPar = 0
for token in iterTokens:
if token == ")":
openPar -= 1
elif token == "(":
openPar += 1
if openPar > 0:
# found the last unclosed parenthesis
break
else:
return []
# 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
ids = []
isId = re.compile(r"\w+$").match
while True:
try:
ids.append(next(iterTokens))
if not isId(ids[-1]):
ids.pop()
break
if not next(iterTokens) == ".":
break
except StopIteration:
break
# lookup the candidate callable matches either using global_matches
# or attr_matches for dotted names
if len(ids) == 1:
callableMatches = self.global_matches(ids[0])
else:
callableMatches = self.attr_matches(".".join(ids[::-1]))
argMatches = []
for callableMatch in callableMatches:
try:
namedArgs = self._default_arguments(eval(callableMatch, self.namespace))
except:
continue
for namedArg in namedArgs:
if namedArg.startswith(text):
argMatches.append("%s=" % namedArg)
return argMatches
|
https://github.com/ipython/ipython/issues/9379
|
Python 2.7.11+ (default, Mar 30 2016, 21:00:42)
Type "copyright", "credits" or "license" for more information.
IPython 5.0.0.dev -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: dException in thread Thread-7:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/interface.py", line 742, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/home/bwillar0/projects/python/ipython/IPython/terminal/ptshell.py", line 55, in gets
m = unicodedata.normalize('NFC', m)
TypeError: normalize() argument 2 must be unicode, not str
|
TypeError
|
def dispatch_custom_completer(self, text):
line = self.line_buffer
if not line.strip():
return None
# Create a little structure to pass all the relevant information about
# the current completion to any custom completer.
event = Bunch()
event.line = line
event.symbol = text
cmd = line.split(None, 1)[0]
event.command = cmd
event.text_until_cursor = self.text_until_cursor
# print "\ncustom:{%s]\n" % event # dbg
# for foo etc, try also to find completer for %foo
if not cmd.startswith(self.magic_escape):
try_magic = self.custom_completers.s_matches(self.magic_escape + cmd)
else:
try_magic = []
for c in itertools.chain(
self.custom_completers.s_matches(cmd),
try_magic,
self.custom_completers.flat_matches(self.text_until_cursor),
):
try:
res = c(event)
if res:
# first, try case sensitive match
withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
if withcase:
return withcase
# if none, then case insensitive ones are ok too
text_low = text.lower()
return [
cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)
]
except TryNext:
pass
return None
|
def dispatch_custom_completer(self, text):
# io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
line = self.line_buffer
if not line.strip():
return None
# Create a little structure to pass all the relevant information about
# the current completion to any custom completer.
event = Bunch()
event.line = line
event.symbol = text
cmd = line.split(None, 1)[0]
event.command = cmd
event.text_until_cursor = self.text_until_cursor
# print "\ncustom:{%s]\n" % event # dbg
# for foo etc, try also to find completer for %foo
if not cmd.startswith(self.magic_escape):
try_magic = self.custom_completers.s_matches(self.magic_escape + cmd)
else:
try_magic = []
for c in itertools.chain(
self.custom_completers.s_matches(cmd),
try_magic,
self.custom_completers.flat_matches(self.text_until_cursor),
):
# print "try",c # dbg
try:
res = c(event)
if res:
# first, try case sensitive match
withcase = [r for r in res if r.startswith(text)]
if withcase:
return withcase
# if none, then case insensitive ones are ok too
text_low = text.lower()
return [r for r in res if r.lower().startswith(text_low)]
except TryNext:
pass
return None
|
https://github.com/ipython/ipython/issues/9379
|
Python 2.7.11+ (default, Mar 30 2016, 21:00:42)
Type "copyright", "credits" or "license" for more information.
IPython 5.0.0.dev -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: dException in thread Thread-7:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/interface.py", line 742, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/home/bwillar0/projects/python/ipython/IPython/terminal/ptshell.py", line 55, in gets
m = unicodedata.normalize('NFC', m)
TypeError: normalize() argument 2 must be unicode, not str
|
TypeError
|
def head(self, kernel_name, path):
return self.get(kernel_name, path, include_body=False)
|
def head(self, kernel_name, path):
self.get(kernel_name, path, include_body=False)
|
https://github.com/ipython/ipython/issues/7237
|
[E 16:39:08.471 NotebookApp] Uncaught exception HEAD /kernelspecs/python3/kernel.css (::1)
HTTPServerRequest(protocol='http', host='localhost:8888', method='HEAD', uri='/kernelspecs/python3/kernel.css', version='HTTP/1.1', remote_ip='::1', headers={'Content-Length': '0', 'Accept-Language': 'en-US,en;q=0.8,gl;q=0.6,sq;q=0.4', 'Accept-Encoding': 'gzip, deflate, sdch', 'Host': 'localhost:8888', 'Accept': '*/*', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Connection': 'keep-alive', 'X-Requested-With': 'XMLHttpRequest', 'Referer': 'http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2'})
Traceback (most recent call last):
File "/Users/bgranger/anaconda/lib/python2.7/site-packages/tornado/web.py", line 1338, in _execute
self.finish()
File "/Users/bgranger/anaconda/lib/python2.7/site-packages/tornado/web.py", line 877, in finish
self.set_etag_header()
File "/Users/bgranger/anaconda/lib/python2.7/site-packages/tornado/web.py", line 1257, in set_etag_header
etag = self.compute_etag()
File "/Users/bgranger/anaconda/lib/python2.7/site-packages/tornado/web.py", line 2185, in compute_etag
version_hash = self._get_cached_version(self.absolute_path)
AttributeError: 'KernelSpecResourceHandler' object has no attribute 'absolute_path'
[E 16:39:08.480 NotebookApp] {
"Content-Length": "0",
"Accept-Language": "en-US,en;q=0.8,gl;q=0.6,sq;q=0.4",
"Accept-Encoding": "gzip, deflate, sdch",
"Connection": "keep-alive",
"Accept": "*/*",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
"Host": "localhost:8888",
"X-Requested-With": "XMLHttpRequest",
"Referer": "http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2"
}
[E 16:39:08.480 NotebookApp] 500 HEAD /kernelspecs/python3/kernel.css (::1) 10.72ms referer=http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2
[I 16:39:08.893 NotebookApp] Kernel shutdown: bd0457da-716d-4fe5-8f13-42614f444fe5
[W 16:39:08.899 NotebookApp] 404 GET /kernelspecs/python3/logo-64x64.png (::1) 3.82ms referer=http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2
[W 16:39:08.902 NotebookApp] 404 GET /kernelspecs/python3/kernel.js (::1) 2.22ms referer=http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2
[I 16:39:08.914 NotebookApp] Kernel started: 6875241d-5bbe-4291-8c8e-467867545143
|
AttributeError
|
def enable(self, app=None):
"""Enable event loop integration with PyQt4.
Parameters
----------
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Notes
-----
This methods sets the PyOS_InputHook for PyQt4, which allows
the PyQt4 to integrate with terminal based applications like
IPython.
If ``app`` is not given we probe for an existing one, and return it if
found. If no existing app is found, we create an :class:`QApplication`
as follows::
from PyQt4 import QtCore
app = QtGui.QApplication(sys.argv)
"""
from IPython.lib.inputhookqt4 import create_inputhook_qt4
from IPython.external.appnope import nope
app, inputhook_qt4 = create_inputhook_qt4(self.manager, app)
self.manager.set_inputhook(inputhook_qt4)
nope()
return app
|
def enable(self, app=None):
"""Enable event loop integration with PyQt4.
Parameters
----------
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Notes
-----
This methods sets the PyOS_InputHook for PyQt4, which allows
the PyQt4 to integrate with terminal based applications like
IPython.
If ``app`` is not given we probe for an existing one, and return it if
found. If no existing app is found, we create an :class:`QApplication`
as follows::
from PyQt4 import QtCore
app = QtGui.QApplication(sys.argv)
"""
from IPython.lib.inputhookqt4 import create_inputhook_qt4
from IPython.external.appnope import nope
app, inputhook_qt4 = create_inputhook_qt4(self, app)
self.manager.set_inputhook(inputhook_qt4)
nope()
return app
|
https://github.com/ipython/ipython/issues/6804
|
In [4]: Traceback (most recent call last):
File "/Users/ehvatum/Desktop/ipython_git/IPython/lib/inputhookqt4.py", line 123, in inputhook_qt4
event_loop.exec_()
KeyboardInterrupt
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 277, in 'calling callback function'
File "/Users/ehvatum/Desktop/ipython_git/IPython/lib/inputhookqt4.py", line 130, in inputhook_qt4
mgr.clear_inputhook()
AttributeError: 'Qt4InputHook' object has no attribute 'clear_inputhook'
If you suspect this is an IPython bug, please report it at:
https://github.com/ipython/ipython/issues
or send an email to the mailing list at ipython-dev@scipy.org
You can print a more detailed traceback right now with "%tb", or use "%debug"
to interactively debug it.
Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
%config Application.verbose_crash=True
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 9, in
load_entry_point('ipython==3.0.0-dev', 'console_scripts', 'ipython')()
File "/Users/ehvatum/Desktop/ipython_git/IPython/init.py", line 120, in start_ipython
return launch_new_instance(argv=argv, **kwargs)
File "/Users/ehvatum/Desktop/ipython_git/IPython/config/application.py", line 549, in launch_instance
app.start()
File "/Users/ehvatum/Desktop/ipython_git/IPython/terminal/ipapp.py", line 372, in start
self.shell.mainloop()
File "/Users/ehvatum/Desktop/ipython_git/IPython/terminal/interactiveshell.py", line 383, in mainloop
self.interact(display_banner=display_banner)
File "/Users/ehvatum/Desktop/ipython_git/IPython/terminal/interactiveshell.py", line 446, in interact
self.hooks.pre_prompt_hook()
File "/Users/ehvatum/Desktop/ipython_git/IPython/core/hooks.py", line 137, in call
return cmd(*args, **kw)
File "/Users/ehvatum/Desktop/ipython_git/IPython/lib/inputhookqt4.py", line 174, in preprompthook_qt4
mgr.set_inputhook(inputhook_qt4)
AttributeError: 'Qt4InputHook' object has no attribute 'set_inputhook'
If you suspect this is an IPython bug, please report it at:
https://github.com/ipython/ipython/issues
or send an email to the mailing list at ipython-dev@scipy.org
You can print a more detailed traceback right now with "%tb", or use "%debug"
to interactively debug it.
Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
%config Application.verbose_crash=True
|
AttributeError
|
def safe_execfile(self, fname, *where, **kw):
"""A safe version of the builtin execfile().
This version will never throw an exception, but instead print
helpful error messages to the screen. This only works on pure
Python files with the .py extension.
Parameters
----------
fname : string
The name of the file to be executed.
where : tuple
One or two namespaces, passed to execfile() as (globals,locals).
If only one is given, it is passed as both.
exit_ignore : bool (False)
If True, then silence SystemExit for non-zero status (it is always
silenced for zero status, as it is so common).
raise_exceptions : bool (False)
If True raise exceptions everywhere. Meant for testing.
"""
kw.setdefault("exit_ignore", False)
kw.setdefault("raise_exceptions", False)
fname = os.path.abspath(os.path.expanduser(fname))
# Make sure we can open the file
try:
with open(fname) as thefile:
pass
except:
warn("Could not open file <%s> for safe execution." % fname)
return
# Find things also in current directory. This is needed to mimic the
# behavior of running a script from the system command line, where
# Python inserts the script's directory into sys.path
dname = os.path.dirname(fname)
with prepended_to_syspath(dname):
try:
py3compat.execfile(fname, *where)
except SystemExit as status:
# If the call was made with 0 or None exit status (sys.exit(0)
# or sys.exit() ), don't bother showing a traceback, as both of
# these are considered normal by the OS:
# > python -c'import sys;sys.exit(0)'; echo $?
# 0
# > python -c'import sys;sys.exit()'; echo $?
# 0
# For other exit status, we show the exception unless
# explicitly silenced, but only in short form.
if kw["raise_exceptions"]:
raise
if status.code and not kw["exit_ignore"]:
self.showtraceback(exception_only=True)
except:
if kw["raise_exceptions"]:
raise
# tb offset is 2 because we wrap execfile
self.showtraceback(tb_offset=2)
|
def safe_execfile(self, fname, *where, **kw):
"""A safe version of the builtin execfile().
This version will never throw an exception, but instead print
helpful error messages to the screen. This only works on pure
Python files with the .py extension.
Parameters
----------
fname : string
The name of the file to be executed.
where : tuple
One or two namespaces, passed to execfile() as (globals,locals).
If only one is given, it is passed as both.
exit_ignore : bool (False)
If True, then silence SystemExit for non-zero status (it is always
silenced for zero status, as it is so common).
raise_exceptions : bool (False)
If True raise exceptions everywhere. Meant for testing.
"""
kw.setdefault("exit_ignore", False)
kw.setdefault("raise_exceptions", False)
fname = os.path.abspath(os.path.expanduser(fname))
# Make sure we can open the file
try:
with open(fname) as thefile:
pass
except:
warn("Could not open file <%s> for safe execution." % fname)
return
# Find things also in current directory. This is needed to mimic the
# behavior of running a script from the system command line, where
# Python inserts the script's directory into sys.path
dname = os.path.dirname(fname)
with prepended_to_syspath(dname):
try:
py3compat.execfile(fname, *where)
except SystemExit as status:
# If the call was made with 0 or None exit status (sys.exit(0)
# or sys.exit() ), don't bother showing a traceback, as both of
# these are considered normal by the OS:
# > python -c'import sys;sys.exit(0)'; echo $?
# 0
# > python -c'import sys;sys.exit()'; echo $?
# 0
# For other exit status, we show the exception unless
# explicitly silenced, but only in short form.
if kw["raise_exceptions"]:
raise
if status.code and not kw["exit_ignore"]:
self.showtraceback(exception_only=True)
except:
if kw["raise_exceptions"]:
raise
self.showtraceback()
|
https://github.com/ipython/ipython/issues/4835
|
root@8e0bcc11822a:~# ipython test.py
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
/usr/lib/python2.7/dist-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
173 else:
174 filename = fname
--> 175 __builtin__.execfile(filename, *where)
/home/coderpad/test.py in <module>()
2 while x < 10:
3 x += 1
----> 4 10 / (5 - x)
5
6 print x
ZeroDivisionError: integer division or modulo by zero
root@8e0bcc11822a:~# ipython --version
0.12.1
|
ZeroDivisionError
|
def check_pid(self, pid):
if os.name == "nt":
try:
import ctypes
# returns 0 if no such process (of ours) exists
# positive int otherwise
p = ctypes.windll.kernel32.OpenProcess(1, 0, pid)
except Exception:
self.log.warn(
"Could not determine whether pid %i is running via `OpenProcess`. "
" Making the likely assumption that it is." % pid
)
return True
return bool(p)
else:
try:
p = Popen(["ps", "x"], stdout=PIPE, stderr=PIPE)
output, _ = p.communicate()
except OSError:
self.log.warn(
"Could not determine whether pid %i is running via `ps x`. "
" Making the likely assumption that it is." % pid
)
return True
pids = list(map(int, re.findall(rb"^\W*\d+", output, re.MULTILINE)))
return pid in pids
|
def check_pid(self, pid):
if os.name == "nt":
try:
import ctypes
# returns 0 if no such process (of ours) exists
# positive int otherwise
p = ctypes.windll.kernel32.OpenProcess(1, 0, pid)
except Exception:
self.log.warn(
"Could not determine whether pid %i is running via `OpenProcess`. "
" Making the likely assumption that it is." % pid
)
return True
return bool(p)
else:
try:
p = Popen(["ps", "x"], stdout=PIPE, stderr=PIPE)
output, _ = p.communicate()
except OSError:
self.log.warn(
"Could not determine whether pid %i is running via `ps x`. "
" Making the likely assumption that it is." % pid
)
return True
pids = list(map(int, re.findall(r"^\W*\d+", output, re.MULTILINE)))
return pid in pids
|
https://github.com/ipython/ipython/issues/4602
|
Traceback (most recent call last):
File "/work/bin/ipcluster3", line 9, in <module>
load_entry_point('ipython==1.1.0', 'console_scripts', 'ipcluster3')()
File "/work/lib/python3.3/site-packages/IPython/config/application.py", line 545, in launch_instance
app.start()
File "/work/lib/python3.3/site-packages/IPython/parallel/apps/ipclusterapp.py", line 604, in start
return self.subapp.start()
File "/work/lib/python3.3/site-packages/IPython/parallel/apps/ipclusterapp.py", line 195, in start
if not self.check_pid(pid):
File "/work/lib/python3.3/site-packages/IPython/parallel/apps/baseapp.py", line 275, in check_pid
pids = list(map(int, re.findall(r'^\W*\d+', output, re.MULTILINE)))
File "/work/lib/python3.3/re.py", line 201, in findall
return _compile(pattern, flags).findall(string)
TypeError: can't use a string pattern on a bytes-like object
|
TypeError
|
def _run_with_debugger(self, code, code_ns, filename=None, bp_line=None, bp_file=None):
"""
Run `code` in debugger with a break point.
Parameters
----------
code : str
Code to execute.
code_ns : dict
A namespace in which `code` is executed.
filename : str
`code` is ran as if it is in `filename`.
bp_line : int, optional
Line number of the break point.
bp_file : str, optional
Path to the file in which break point is specified.
`filename` is used if not given.
Raises
------
UsageError
If the break point given by `bp_line` is not valid.
"""
deb = debugger.Pdb(self.shell.colors)
# reset Breakpoint state, which is moronically kept
# in a class
bdb.Breakpoint.next = 1
bdb.Breakpoint.bplist = {}
bdb.Breakpoint.bpbynumber = [None]
if bp_line is not None:
# Set an initial breakpoint to stop execution
maxtries = 10
bp_file = bp_file or filename
checkline = deb.checkline(bp_file, bp_line)
if not checkline:
for bp in range(bp_line + 1, bp_line + maxtries + 1):
if deb.checkline(bp_file, bp):
break
else:
msg = (
"\nI failed to find a valid line to set "
"a breakpoint\n"
"after trying up to line: %s.\n"
"Please set a valid breakpoint manually "
"with the -b option." % bp
)
raise UsageError(msg)
# if we find a good linenumber, set the breakpoint
deb.do_break("%s:%s" % (bp_file, bp_line))
if filename:
# Mimic Pdb._runscript(...)
deb._wait_for_mainpyfile = True
deb.mainpyfile = deb.canonic(filename)
# Start file run
print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
try:
if filename:
# save filename so it can be used by methods on the deb object
deb._exec_filename = filename
while True:
try:
deb.run(code, code_ns)
except Restart:
print("Restarting")
if filename:
deb._wait_for_mainpyfile = True
deb.mainpyfile = deb.canonic(filename)
continue
else:
break
except:
etype, value, tb = sys.exc_info()
# Skip three frames in the traceback: the %run one,
# one inside bdb.py, and the command-line typed by the
# user (run by exec in pdb itself).
self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
|
def _run_with_debugger(self, code, code_ns, filename=None, bp_line=None, bp_file=None):
"""
Run `code` in debugger with a break point.
Parameters
----------
code : str
Code to execute.
code_ns : dict
A namespace in which `code` is executed.
filename : str
`code` is ran as if it is in `filename`.
bp_line : int, optional
Line number of the break point.
bp_file : str, optional
Path to the file in which break point is specified.
`filename` is used if not given.
Raises
------
UsageError
If the break point given by `bp_line` is not valid.
"""
deb = debugger.Pdb(self.shell.colors)
# reset Breakpoint state, which is moronically kept
# in a class
bdb.Breakpoint.next = 1
bdb.Breakpoint.bplist = {}
bdb.Breakpoint.bpbynumber = [None]
if bp_line is not None:
# Set an initial breakpoint to stop execution
maxtries = 10
bp_file = bp_file or filename
checkline = deb.checkline(bp_file, bp_line)
if not checkline:
for bp in range(bp_line + 1, bp_line + maxtries + 1):
if deb.checkline(bp_file, bp):
break
else:
msg = (
"\nI failed to find a valid line to set "
"a breakpoint\n"
"after trying up to line: %s.\n"
"Please set a valid breakpoint manually "
"with the -b option." % bp
)
raise UsageError(msg)
# if we find a good linenumber, set the breakpoint
deb.do_break("%s:%s" % (bp_file, bp_line))
if filename:
# Mimic Pdb._runscript(...)
deb._wait_for_mainpyfile = True
deb.mainpyfile = deb.canonic(filename)
# Start file run
print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
try:
if filename:
# save filename so it can be used by methods on the deb object
deb._exec_filename = filename
deb.run(code, code_ns)
except:
etype, value, tb = sys.exc_info()
# Skip three frames in the traceback: the %run one,
# one inside bdb.py, and the command-line typed by the
# user (run by exec in pdb itself).
self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
|
https://github.com/ipython/ipython/issues/3043
|
In [1]: %run -d ~/t.py
Breakpoint 1 at /home/sk/t.py:1
NOTE: Enter 'c' at the ipdb> prompt to start your script.
/home/sk/t.py(1)<module>()
1---> 1 from sympy import *
2 x = Symbol('x')
3 #bessely(0,x).series(x)
ipdb> n
/home/sk/t.py(2)<module>()
1 1 from sympy import *
----> 2 x = Symbol('x')
3 #bessely(0,x).series(x)
ipdb> n
/home/sk/t.py(5)<module>()
4 #sin(asin(3), evaluate=False).is_rational
----> 5 n = Symbol('n', integer=True)
6 #Sum(x**n, (n, 0, S.Infinity)).doit()
ipdb> restart
---------------------------------------------------------------------------
Restart Traceback (most recent call last)
/home/sk/src/ipython/IPython/utils/py3compat.pyc in execfile(fname, *where)
181 else:
182 filename = fname
--> 183 __builtin__.execfile(filename, *where)
/home/sk/t.py in <module>()
3 #bessely(0,x).series(x)
4 #sin(asin(3), evaluate=False).is_rational
----> 5 n = Symbol('n', integer=True)
6 #Sum(x**n, (n, 0, S.Infinity)).doit()
7 summation(2**n - 10,(n,0,oo))
/home/sk/t.py in <module>()
3 #bessely(0,x).series(x)
4 #sin(asin(3), evaluate=False).is_rational
----> 5 n = Symbol('n', integer=True)
6 #Sum(x**n, (n, 0, S.Infinity)).doit()
7 summation(2**n - 10,(n,0,oo))
/usr/lib/python2.6/bdb.pyc in trace_dispatch(self, frame, event, arg)
44 return # None
45 if event == 'line':
---> 46 return self.dispatch_line(frame)
47 if event == 'call':
48 return self.dispatch_call(frame, arg)
/usr/lib/python2.6/bdb.pyc in dispatch_line(self, frame)
62 def dispatch_line(self, frame):
63 if self.stop_here(frame) or self.break_here(frame):
---> 64 self.user_line(frame)
65 if self.quitting: raise BdbQuit
66 return self.trace_dispatch
/usr/lib/python2.6/pdb.pyc in user_line(self, frame)
148 self._wait_for_mainpyfile = 0
149 if self.bp_commands(frame):
--> 150 self.interaction(frame, None)
151
152 def bp_commands(self,frame):
/home/sk/src/ipython/IPython/core/debugger.pyc in interaction(self, frame, traceback)
259 def interaction(self, frame, traceback):
260 self.shell.set_completer_frame(frame)
--> 261 OldPdb.interaction(self, frame, traceback)
262
263 def new_do_up(self, arg):
/usr/lib/python2.6/pdb.pyc in interaction(self, frame, traceback)
196 self.setup(frame, traceback)
197 self.print_stack_entry(self.stack[self.curindex])
--> 198 self.cmdloop()
199 self.forget()
200
/usr/lib/python2.6/cmd.pyc in cmdloop(self, intro)
140 line = line.rstrip('\r\n')
141 line = self.precmd(line)
--> 142 stop = self.onecmd(line)
143 stop = self.postcmd(stop, line)
144 self.postloop()
/usr/lib/python2.6/pdb.pyc in onecmd(self, line)
265 """
266 if not self.commands_defining:
--> 267 return cmd.Cmd.onecmd(self, line)
268 else:
269 return self.handle_command_def(line)
/usr/lib/python2.6/cmd.pyc in onecmd(self, line)
217 except AttributeError:
218 return self.default(line)
--> 219 return func(arg)
220
221 def emptyline(self):
/usr/lib/python2.6/pdb.pyc in do_run(self, arg)
659 sys.argv = shlex.split(arg)
660 sys.argv[:0] = argv0
--> 661 raise Restart
662
663 do_restart = do_run
Restart:
In [2]:
|
AttributeError
|
def win32_clipboard_get():
"""Get the current clipboard's text on Windows.
Requires Mark Hammond's pywin32 extensions.
"""
try:
import win32clipboard
except ImportError:
raise TryNext(
"Getting text from the clipboard requires the pywin32 "
"extensions: http://sourceforge.net/projects/pywin32/"
)
win32clipboard.OpenClipboard()
try:
text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
except TypeError:
try:
text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
except TypeError:
raise ClipboardEmpty
finally:
win32clipboard.CloseClipboard()
return text
|
def win32_clipboard_get():
"""Get the current clipboard's text on Windows.
Requires Mark Hammond's pywin32 extensions.
"""
try:
import win32clipboard
except ImportError:
raise TryNext(
"Getting text from the clipboard requires the pywin32 "
"extensions: http://sourceforge.net/projects/pywin32/"
)
win32clipboard.OpenClipboard()
text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
# FIXME: convert \r\n to \n?
win32clipboard.CloseClipboard()
return text
|
https://github.com/ipython/ipython/issues/3386
|
In [1]: %paste
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-86b9186405a3> in <module>()
----> 1 get_ipython().magic('paste')
/usr/local/lib/python3.3/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
2135 magic_name, _, magic_arg_s = arg_s.partition(' ')
2136 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2137 return self.run_line_magic(magic_name, magic_arg_s)
2138
2139 #-------------------------------------------------------------------------
/usr/local/lib/python3.3/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
2061 args.append(sys._getframe(stack_depth).f_locals)
2062 with self.builtin_trap:
-> 2063 result = fn(*args)
2064 return result
2065
/usr/local/lib/python3.3/site-packages/IPython/frontend/terminal/interactiveshell.py in paste(self, parameter_s)
/usr/local/lib/python3.3/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
190 # but it's overkill for just that one bit of state.
191 def magic_deco(arg):
--> 192 call = lambda f, *a, **k: f(*a, **k)
193
194 if isinstance(arg, collections.Callable):
/usr/local/lib/python3.3/site-packages/IPython/frontend/terminal/interactiveshell.py in paste(self, parameter_s)
282 if 'q' not in opts:
283 write = self.shell.write
--> 284 write(self.shell.pycolorize(block))
285 if not block.endswith('\n'):
286 write('\n')
/usr/local/lib/python3.3/site-packages/IPython/core/interactiveshell.py in <lambda>(src)
575 # Python source parser/formatter for syntax highlighting
576 pyformat = PyColorize.Parser().format
--> 577 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
578
579 def init_pushd_popd_magic(self):
/usr/local/lib/python3.3/site-packages/IPython/utils/PyColorize.py in format(self, raw, out, scheme)
127
128 def format(self, raw, out = None, scheme = ''):
--> 129 return self.format2(raw, out, scheme)[0]
130
131 def format2(self, raw, out = None, scheme = ''):
/usr/local/lib/python3.3/site-packages/IPython/utils/PyColorize.py in format2(self, raw, out, scheme)
174 lines_append = self.lines.append
175 while 1:
--> 176 pos = raw_find('\n', pos) + 1
177 if not pos: break
178 lines_append(pos)
TypeError: Type str doesn't support the buffer API
|
TypeError
|
def tkinter_clipboard_get():
"""Get the clipboard's text using Tkinter.
This is the default on systems that are not Windows or OS X. It may
interfere with other UI toolkits and should be replaced with an
implementation that uses that toolkit.
"""
try:
from tkinter import Tk, TclError # Py 3
except ImportError:
try:
from Tkinter import Tk, TclError # Py 2
except ImportError:
raise TryNext(
"Getting text from the clipboard on this platform requires Tkinter."
)
root = Tk()
root.withdraw()
try:
text = root.clipboard_get()
except TclError:
raise ClipboardEmpty
finally:
root.destroy()
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
return text
|
def tkinter_clipboard_get():
"""Get the clipboard's text using Tkinter.
This is the default on systems that are not Windows or OS X. It may
interfere with other UI toolkits and should be replaced with an
implementation that uses that toolkit.
"""
try:
from tkinter import Tk # Py 3
except ImportError:
try:
from Tkinter import Tk # Py 2
except ImportError:
raise TryNext(
"Getting text from the clipboard on this platform requires Tkinter."
)
root = Tk()
root.withdraw()
text = root.clipboard_get()
root.destroy()
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
return text
|
https://github.com/ipython/ipython/issues/3386
|
In [1]: %paste
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-86b9186405a3> in <module>()
----> 1 get_ipython().magic('paste')
/usr/local/lib/python3.3/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
2135 magic_name, _, magic_arg_s = arg_s.partition(' ')
2136 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2137 return self.run_line_magic(magic_name, magic_arg_s)
2138
2139 #-------------------------------------------------------------------------
/usr/local/lib/python3.3/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
2061 args.append(sys._getframe(stack_depth).f_locals)
2062 with self.builtin_trap:
-> 2063 result = fn(*args)
2064 return result
2065
/usr/local/lib/python3.3/site-packages/IPython/frontend/terminal/interactiveshell.py in paste(self, parameter_s)
/usr/local/lib/python3.3/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
190 # but it's overkill for just that one bit of state.
191 def magic_deco(arg):
--> 192 call = lambda f, *a, **k: f(*a, **k)
193
194 if isinstance(arg, collections.Callable):
/usr/local/lib/python3.3/site-packages/IPython/frontend/terminal/interactiveshell.py in paste(self, parameter_s)
282 if 'q' not in opts:
283 write = self.shell.write
--> 284 write(self.shell.pycolorize(block))
285 if not block.endswith('\n'):
286 write('\n')
/usr/local/lib/python3.3/site-packages/IPython/core/interactiveshell.py in <lambda>(src)
575 # Python source parser/formatter for syntax highlighting
576 pyformat = PyColorize.Parser().format
--> 577 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
578
579 def init_pushd_popd_magic(self):
/usr/local/lib/python3.3/site-packages/IPython/utils/PyColorize.py in format(self, raw, out, scheme)
127
128 def format(self, raw, out = None, scheme = ''):
--> 129 return self.format2(raw, out, scheme)[0]
130
131 def format2(self, raw, out = None, scheme = ''):
/usr/local/lib/python3.3/site-packages/IPython/utils/PyColorize.py in format2(self, raw, out, scheme)
174 lines_append = self.lines.append
175 while 1:
--> 176 pos = raw_find('\n', pos) + 1
177 if not pos: break
178 lines_append(pos)
TypeError: Type str doesn't support the buffer API
|
TypeError
|
def paste(self, parameter_s=""):
"""Paste & execute a pre-formatted code block from clipboard.
The text is pulled directly from the clipboard without user
intervention and printed back on the screen before execution (unless
the -q flag is given to force quiet mode).
The block is dedented prior to execution to enable execution of method
definitions. '>' and '+' characters at the beginning of a line are
ignored, to allow pasting directly from e-mails, diff files and
doctests (the '...' continuation prompt is also stripped). The
executed block is also assigned to variable named 'pasted_block' for
later editing with '%edit pasted_block'.
You can also pass a variable name as an argument, e.g. '%paste foo'.
This assigns the pasted block to variable 'foo' as string, without
executing it (preceding >>> and + is still stripped).
Options
-------
-r: re-executes the block previously entered by cpaste.
-q: quiet mode: do not echo the pasted text back to the terminal.
IPython statements (magics, shell escapes) are not supported (yet).
See also
--------
cpaste: manually paste code into terminal until you mark its end.
"""
opts, name = self.parse_options(parameter_s, "rq", mode="string")
if "r" in opts:
self.rerun_pasted()
return
try:
block = self.shell.hooks.clipboard_get()
except TryNext as clipboard_exc:
message = getattr(clipboard_exc, "args")
if message:
error(message[0])
else:
error("Could not get text from the clipboard.")
return
except ClipboardEmpty:
raise UsageError("The clipboard appears to be empty")
# By default, echo back to terminal unless quiet mode is requested
if "q" not in opts:
write = self.shell.write
write(self.shell.pycolorize(block))
if not block.endswith("\n"):
write("\n")
write("## -- End pasted text --\n")
self.store_or_execute(block, name)
|
def paste(self, parameter_s=""):
"""Paste & execute a pre-formatted code block from clipboard.
The text is pulled directly from the clipboard without user
intervention and printed back on the screen before execution (unless
the -q flag is given to force quiet mode).
The block is dedented prior to execution to enable execution of method
definitions. '>' and '+' characters at the beginning of a line are
ignored, to allow pasting directly from e-mails, diff files and
doctests (the '...' continuation prompt is also stripped). The
executed block is also assigned to variable named 'pasted_block' for
later editing with '%edit pasted_block'.
You can also pass a variable name as an argument, e.g. '%paste foo'.
This assigns the pasted block to variable 'foo' as string, without
executing it (preceding >>> and + is still stripped).
Options
-------
-r: re-executes the block previously entered by cpaste.
-q: quiet mode: do not echo the pasted text back to the terminal.
IPython statements (magics, shell escapes) are not supported (yet).
See also
--------
cpaste: manually paste code into terminal until you mark its end.
"""
opts, name = self.parse_options(parameter_s, "rq", mode="string")
if "r" in opts:
self.rerun_pasted()
return
try:
block = self.shell.hooks.clipboard_get()
except TryNext as clipboard_exc:
message = getattr(clipboard_exc, "args")
if message:
error(message[0])
else:
error("Could not get text from the clipboard.")
return
# By default, echo back to terminal unless quiet mode is requested
if "q" not in opts:
write = self.shell.write
write(self.shell.pycolorize(block))
if not block.endswith("\n"):
write("\n")
write("## -- End pasted text --\n")
self.store_or_execute(block, name)
|
https://github.com/ipython/ipython/issues/3386
|
In [1]: %paste
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-86b9186405a3> in <module>()
----> 1 get_ipython().magic('paste')
/usr/local/lib/python3.3/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
2135 magic_name, _, magic_arg_s = arg_s.partition(' ')
2136 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2137 return self.run_line_magic(magic_name, magic_arg_s)
2138
2139 #-------------------------------------------------------------------------
/usr/local/lib/python3.3/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
2061 args.append(sys._getframe(stack_depth).f_locals)
2062 with self.builtin_trap:
-> 2063 result = fn(*args)
2064 return result
2065
/usr/local/lib/python3.3/site-packages/IPython/frontend/terminal/interactiveshell.py in paste(self, parameter_s)
/usr/local/lib/python3.3/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
190 # but it's overkill for just that one bit of state.
191 def magic_deco(arg):
--> 192 call = lambda f, *a, **k: f(*a, **k)
193
194 if isinstance(arg, collections.Callable):
/usr/local/lib/python3.3/site-packages/IPython/frontend/terminal/interactiveshell.py in paste(self, parameter_s)
282 if 'q' not in opts:
283 write = self.shell.write
--> 284 write(self.shell.pycolorize(block))
285 if not block.endswith('\n'):
286 write('\n')
/usr/local/lib/python3.3/site-packages/IPython/core/interactiveshell.py in <lambda>(src)
575 # Python source parser/formatter for syntax highlighting
576 pyformat = PyColorize.Parser().format
--> 577 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
578
579 def init_pushd_popd_magic(self):
/usr/local/lib/python3.3/site-packages/IPython/utils/PyColorize.py in format(self, raw, out, scheme)
127
128 def format(self, raw, out = None, scheme = ''):
--> 129 return self.format2(raw, out, scheme)[0]
130
131 def format2(self, raw, out = None, scheme = ''):
/usr/local/lib/python3.3/site-packages/IPython/utils/PyColorize.py in format2(self, raw, out, scheme)
174 lines_append = self.lines.append
175 while 1:
--> 176 pos = raw_find('\n', pos) + 1
177 if not pos: break
178 lines_append(pos)
TypeError: Type str doesn't support the buffer API
|
TypeError
|
def tunnel_to_kernel(connection_info, sshserver, sshkey=None):
"""tunnel connections to a kernel via ssh
This will open four SSH tunnels from localhost on this machine to the
ports associated with the kernel. They can be either direct
localhost-localhost tunnels, or if an intermediate server is necessary,
the kernel must be listening on a public IP.
Parameters
----------
connection_info : dict or str (path)
Either a connection dict, or the path to a JSON connection file
sshserver : str
The ssh sever to use to tunnel to the kernel. Can be a full
`user@server:port` string. ssh config aliases are respected.
sshkey : str [optional]
Path to file containing ssh key to use for authentication.
Only necessary if your ssh config does not already associate
a keyfile with the host.
Returns
-------
(shell, iopub, stdin, hb) : ints
The four ports on localhost that have been forwarded to the kernel.
"""
if isinstance(connection_info, basestring):
# it's a path, unpack it
with open(connection_info) as f:
connection_info = json.loads(f.read())
cf = connection_info
lports = tunnel.select_random_ports(4)
rports = cf["shell_port"], cf["iopub_port"], cf["stdin_port"], cf["hb_port"]
remote_ip = cf["ip"]
if tunnel.try_passwordless_ssh(sshserver, sshkey):
password = False
else:
password = getpass("SSH Password for %s: " % cast_bytes_py2(sshserver))
for lp, rp in zip(lports, rports):
tunnel.ssh_tunnel(lp, rp, sshserver, remote_ip, sshkey, password)
return tuple(lports)
|
def tunnel_to_kernel(connection_info, sshserver, sshkey=None):
"""tunnel connections to a kernel via ssh
This will open four SSH tunnels from localhost on this machine to the
ports associated with the kernel. They can be either direct
localhost-localhost tunnels, or if an intermediate server is necessary,
the kernel must be listening on a public IP.
Parameters
----------
connection_info : dict or str (path)
Either a connection dict, or the path to a JSON connection file
sshserver : str
The ssh sever to use to tunnel to the kernel. Can be a full
`user@server:port` string. ssh config aliases are respected.
sshkey : str [optional]
Path to file containing ssh key to use for authentication.
Only necessary if your ssh config does not already associate
a keyfile with the host.
Returns
-------
(shell, iopub, stdin, hb) : ints
The four ports on localhost that have been forwarded to the kernel.
"""
if isinstance(connection_info, basestring):
# it's a path, unpack it
with open(connection_info) as f:
connection_info = json.loads(f.read())
cf = connection_info
lports = tunnel.select_random_ports(4)
rports = cf["shell_port"], cf["iopub_port"], cf["stdin_port"], cf["hb_port"]
remote_ip = cf["ip"]
if tunnel.try_passwordless_ssh(sshserver, sshkey):
password = False
else:
password = getpass("SSH Password for %s: " % sshserver)
for lp, rp in zip(lports, rports):
tunnel.ssh_tunnel(lp, rp, sshserver, remote_ip, sshkey, password)
return tuple(lports)
|
https://github.com/ipython/ipython/issues/1824
|
[IPythonQtConsoleApp] Could not setup tunnels
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\frontend\consoleapp.py", line 289, in init_ssh
newports = tunnel_to_kernel(info, self.sshserver, self.sshkey)
File "C:\Python27\lib\site-packages\IPython\lib\kernel.py", line 248, in tunnel_to_kernel
password = getpass("SSH Password for %s: "%sshserver)
File "C:\Python27\lib\getpass.py", line 95, in win_getpass
msvcrt.putch(c)
TypeError: must be char, not unicode
|
TypeError
|
def init_kernel(self):
"""Create the Kernel object itself"""
shell_stream = ZMQStream(self.shell_socket)
control_stream = ZMQStream(self.control_socket)
kernel_factory = import_item(str(self.kernel_class))
kernel = kernel_factory(
parent=self,
session=self.session,
shell_streams=[shell_stream, control_stream],
iopub_socket=self.iopub_socket,
stdin_socket=self.stdin_socket,
log=self.log,
profile_dir=self.profile_dir,
user_ns=self.user_ns,
)
kernel.record_ports(self.ports)
self.kernel = kernel
|
def init_kernel(self):
"""Create the Kernel object itself"""
shell_stream = ZMQStream(self.shell_socket)
control_stream = ZMQStream(self.control_socket)
kernel_factory = import_item(str(self.kernel_class))
kernel = kernel_factory(
parent=self,
session=self.session,
shell_streams=[shell_stream, control_stream],
iopub_socket=self.iopub_socket,
stdin_socket=self.stdin_socket,
log=self.log,
profile_dir=self.profile_dir,
)
kernel.record_ports(self.ports)
self.kernel = kernel
|
https://github.com/ipython/ipython/issues/4005
|
In [24]: IPython.start_kernel()
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-24-3a50fd41fe8b> in <module>()
----> 1 IPython.start_kernel()
/usr/local/lib/python2.7/site-packages/IPython/__init__.pyc in start_kernel(argv, **kwargs)
141 such as `config`.
142 """
--> 143 from IPython.kernel.zmq.kernelapp import launch_new_instance
144 return launch_new_instance(argv=argv, **kwargs)
145
ImportError: cannot import name launch_new_instance
|
ImportError
|
def init_profile_dir(self):
"""initialize the profile dir"""
self._in_init_profile_dir = True
if self.profile_dir is not None:
# already ran
return
try:
# location explicitly specified:
location = self.config.ProfileDir.location
except AttributeError:
# location not specified, find by profile name
try:
p = ProfileDir.find_profile_dir_by_name(
self.ipython_dir, self.profile, self.config
)
except ProfileDirError:
# not found, maybe create it (always create default profile)
if self.auto_create or self.profile == "default":
try:
p = ProfileDir.create_profile_dir_by_name(
self.ipython_dir, self.profile, self.config
)
except ProfileDirError:
self.log.fatal("Could not create profile: %r" % self.profile)
self.exit(1)
else:
self.log.info("Created profile dir: %r" % p.location)
else:
self.log.fatal("Profile %r not found." % self.profile)
self.exit(1)
else:
self.log.info("Using existing profile dir: %r" % p.location)
else:
# location is fully specified
try:
p = ProfileDir.find_profile_dir(location, self.config)
except ProfileDirError:
# not found, maybe create it
if self.auto_create:
try:
p = ProfileDir.create_profile_dir(location, self.config)
except ProfileDirError:
self.log.fatal("Could not create profile directory: %r" % location)
self.exit(1)
else:
self.log.info("Creating new profile dir: %r" % location)
else:
self.log.fatal("Profile directory %r not found." % location)
self.exit(1)
else:
self.log.info("Using existing profile dir: %r" % location)
self.profile_dir = p
self.config_file_paths.append(p.location)
self._in_init_profile_dir = False
|
def init_profile_dir(self):
"""initialize the profile dir"""
try:
# location explicitly specified:
location = self.config.ProfileDir.location
except AttributeError:
# location not specified, find by profile name
try:
p = ProfileDir.find_profile_dir_by_name(
self.ipython_dir, self.profile, self.config
)
except ProfileDirError:
# not found, maybe create it (always create default profile)
if self.auto_create or self.profile == "default":
try:
p = ProfileDir.create_profile_dir_by_name(
self.ipython_dir, self.profile, self.config
)
except ProfileDirError:
self.log.fatal("Could not create profile: %r" % self.profile)
self.exit(1)
else:
self.log.info("Created profile dir: %r" % p.location)
else:
self.log.fatal("Profile %r not found." % self.profile)
self.exit(1)
else:
self.log.info("Using existing profile dir: %r" % p.location)
else:
# location is fully specified
try:
p = ProfileDir.find_profile_dir(location, self.config)
except ProfileDirError:
# not found, maybe create it
if self.auto_create:
try:
p = ProfileDir.create_profile_dir(location, self.config)
except ProfileDirError:
self.log.fatal("Could not create profile directory: %r" % location)
self.exit(1)
else:
self.log.info("Creating new profile dir: %r" % location)
else:
self.log.fatal("Profile directory %r not found." % location)
self.exit(1)
else:
self.log.info("Using existing profile dir: %r" % location)
self.profile_dir = p
self.config_file_paths.append(p.location)
|
https://github.com/ipython/ipython/issues/3837
|
$ ipython notebook --NotebookApp.mathjax_url='foo'
Traceback (most recent call last):
File "/usr/local/share/python/ipython", line 9, in <module>
load_entry_point('ipython==1.0.dev', 'console_scripts', 'ipython')()
File "/Users/bussonniermatthias/ipython/IPython/__init__.py", line 118, in start_ipython
return launch_new_instance(argv=argv, **kwargs)
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 538, in launch_instance
app.initialize(argv)
File "<string>", line 2, in initialize
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 89, in catch_config_error
return method(app, *args, **kwargs)
File "/Users/bussonniermatthias/ipython/IPython/terminal/ipapp.py", line 316, in initialize
super(TerminalIPythonApp, self).initialize(argv)
File "<string>", line 2, in initialize
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 89, in catch_config_error
return method(app, *args, **kwargs)
File "/Users/bussonniermatthias/ipython/IPython/core/application.py", line 347, in initialize
self.parse_command_line(argv)
File "/Users/bussonniermatthias/ipython/IPython/terminal/ipapp.py", line 311, in parse_command_line
return super(TerminalIPythonApp, self).parse_command_line(argv)
File "<string>", line 2, in parse_command_line
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 89, in catch_config_error
return method(app, *args, **kwargs)
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 468, in parse_command_line
return self.initialize_subcommand(subc, subargv)
File "<string>", line 2, in initialize_subcommand
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 89, in catch_config_error
return method(app, *args, **kwargs)
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 407, in initialize_subcommand
self.subapp.initialize(argv)
File "<string>", line 2, in initialize
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 89, in catch_config_error
return method(app, *args, **kwargs)
File "/Users/bussonniermatthias/ipython/IPython/html/notebookapp.py", line 661, in initialize
super(NotebookApp, self).initialize(argv)
File "<string>", line 2, in initialize
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 89, in catch_config_error
return method(app, *args, **kwargs)
File "/Users/bussonniermatthias/ipython/IPython/core/application.py", line 347, in initialize
self.parse_command_line(argv)
File "/Users/bussonniermatthias/ipython/IPython/html/notebookapp.py", line 478, in parse_command_line
super(NotebookApp, self).parse_command_line(argv)
File "<string>", line 2, in parse_command_line
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 89, in catch_config_error
return method(app, *args, **kwargs)
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 493, in parse_command_line
self.update_config(config)
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 392, in update_config
self.config = newconfig
File "/Users/bussonniermatthias/ipython/IPython/utils/traitlets.py", line 319, in __set__
obj._notify_trait(self.name, old_value, new_value)
File "/Users/bussonniermatthias/ipython/IPython/utils/traitlets.py", line 470, in _notify_trait
c(name, old_value, new_value)
File "/Users/bussonniermatthias/ipython/IPython/config/application.py", line 241, in _config_changed
SingletonConfigurable._config_changed(self, name, old, new)
File "/Users/bussonniermatthias/ipython/IPython/config/configurable.py", line 171, in _config_changed
self._load_config(new, traits=traits, section_names=section_names)
File "/Users/bussonniermatthias/ipython/IPython/config/configurable.py", line 155, in _load_config
setattr(self, name, deepcopy(config_value))
File "/Users/bussonniermatthias/ipython/IPython/utils/traitlets.py", line 316, in __set__
old_value = self.__get__(obj)
File "/Users/bussonniermatthias/ipython/IPython/utils/traitlets.py", line 297, in __get__
value = obj._trait_dyn_inits[self.name](obj)
File "/Users/bussonniermatthias/ipython/IPython/html/notebookapp.py", line 446, in _mathjax_url_default
mathjax = filefind(os.path.join('mathjax', 'MathJax.js'), self.static_file_path)
File "/Users/bussonniermatthias/ipython/IPython/html/notebookapp.py", line 434, in static_file_path
return self.extra_static_paths + [DEFAULT_STATIC_FILES_PATH]
File "/Users/bussonniermatthias/ipython/IPython/utils/traitlets.py", line 297, in __get__
value = obj._trait_dyn_inits[self.name](obj)
File "/Users/bussonniermatthias/ipython/IPython/html/notebookapp.py", line 429, in _extra_static_paths_default
return [os.path.join(self.profile_dir.location, 'static')]
|
catch_config_error
|
def from_filename(self, filename, resources=None, **kw):
"""
Convert a notebook from a notebook file.
Parameters
----------
filename : str
Full filename of the notebook file to open and convert.
"""
# Pull the metadata from the filesystem.
if resources is None:
resources = ResourcesDict()
if not "metadata" in resources or resources["metadata"] == "":
resources["metadata"] = ResourcesDict()
basename = os.path.basename(filename)
notebook_name = basename[: basename.rfind(".")]
resources["metadata"]["name"] = notebook_name
modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(filename))
resources["metadata"]["modified_date"] = modified_date.strftime("%B %d, %Y")
with io.open(filename) as f:
return self.from_notebook_node(
nbformat.read(f, "json"), resources=resources, **kw
)
|
def from_filename(self, filename, resources=None, **kw):
"""
Convert a notebook from a notebook file.
Parameters
----------
filename : str
Full filename of the notebook file to open and convert.
"""
# Pull the metadata from the filesystem.
if resources is None:
resources = ResourcesDict()
if not "metadata" in resources or resources["metadata"] == "":
resources["metadata"] = ResourcesDict()
basename = os.path.basename(filename)
notebook_name = basename[: basename.rfind(".")]
resources["metadata"]["name"] = notebook_name
modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(filename))
resources["metadata"]["modified_date"] = modified_date.strftime("%B %-d, %Y")
with io.open(filename) as f:
return self.from_notebook_node(
nbformat.read(f, "json"), resources=resources, **kw
)
|
https://github.com/ipython/ipython/issues/3719
|
C:\Users\jorgenst\notebooks> ipython nbconvert --format=basic_html .\Simple_pylab.ipynb
Traceback (most recent call last):
File "c:\Python27\Scripts\ipython-script.py", line 8, in <module>
load_entry_point('ipython==1.0dev', 'console_scripts', 'ipython')()
File "c:\python27\lib\site-packages\ipython-1.0dev-py2.7.egg\IPython\__init__.py", line 118, in start_ipython
return launch_new_instance(argv=argv, **kwargs)
File "c:\python27\lib\site-packages\ipython-1.0dev-py2.7.egg\IPython\config\application.py", line 539, in launch_instance
app.start()
File "c:\python27\lib\site-packages\ipython-1.0dev-py2.7.egg\IPython\terminal\ipapp.py", line 362, in start
return self.subapp.start()
File "c:\python27\lib\site-packages\ipython-1.0dev-py2.7.egg\IPython\nbconvert\nbconvertapp.py", line 176, in start
self.convert_notebooks()
File "c:\python27\lib\site-packages\ipython-1.0dev-py2.7.egg\IPython\nbconvert\nbconvertapp.py", line 197, in convert_notebooks
config=self.config)
File "c:\python27\lib\site-packages\ipython-1.0dev-py2.7.egg\IPython\nbconvert\exporters\export.py", line 61, in decorator
return f(*args, **kwargs)
File "c:\python27\lib\site-packages\ipython-1.0dev-py2.7.egg\IPython\nbconvert\exporters\export.py", line 214, in export_by_name
return globals()[function_name](nb, **kw)
File "c:\python27\lib\site-packages\ipython-1.0dev-py2.7.egg\IPython\nbconvert\exporters\export.py", line 61, in decorator
return f(*args, **kwargs)
File "c:\python27\lib\site-packages\ipython-1.0dev-py2.7.egg\IPython\nbconvert\exporters\export.py", line 149, in export_basic_html
return export(BasicHTMLExporter, nb, **kw)
File "c:\python27\lib\site-packages\ipython-1.0dev-py2.7.egg\IPython\nbconvert\exporters\export.py", line 61, in decorator
return f(*args, **kwargs)
File "c:\python27\lib\site-packages\ipython-1.0dev-py2.7.egg\IPython\nbconvert\exporters\export.py", line 122, in export
output, resources = exporter_instance.from_filename(nb, resources)
File "c:\python27\lib\site-packages\ipython-1.0dev-py2.7.egg\IPython\nbconvert\exporters\exporter.py", line 218, in from_filename
resources['metadata']['modified_date'] = modified_date.strftime("%B %-d, %Y")
ValueError: Invalid format string
If you suspect this is an IPython bug, please report it at:
https://github.com/ipython/ipython/issues
or send an email to the mailing list at ipython-dev@scipy.org
You can print a more detailed traceback right now with "%tb", or use "%debug"
to interactively debug it.
Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
c.Application.verbose_crash=True
|
ValueError
|
def interaction(self, frame, traceback):
self.shell.set_completer_frame(frame)
while True:
try:
OldPdb.interaction(self, frame, traceback)
except KeyboardInterrupt:
self.shell.write("\nKeyboardInterrupt\n")
else:
break
|
def interaction(self, frame, traceback):
self.shell.set_completer_frame(frame)
OldPdb.interaction(self, frame, traceback)
|
https://github.com/ipython/ipython/issues/3786
|
ipdb> ---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-2-51af4340c641> in <module>()
----> 1 get_ipython().magic(u'debug ')
/home/fperez/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s)
2158 magic_name, _, magic_arg_s = arg_s.partition(' ')
2159 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2160 return self.run_line_magic(magic_name, magic_arg_s)
2161
2162 #-------------------------------------------------------------------------
/home/fperez/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in run_line_magic(self, magic_name, line)
2079 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2080 with self.builtin_trap:
-> 2081 result = fn(*args,**kwargs)
2082 return result
2083
/home/fperez/usr/lib/python2.7/site-packages/IPython/core/magics/execution.pyc in debug(self, line, cell)
/home/fperez/usr/lib/python2.7/site-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k)
189 # but it's overkill for just that one bit of state.
190 def magic_deco(arg):
--> 191 call = lambda f, *a, **k: f(*a, **k)
192
193 if callable(arg):
/home/fperez/usr/lib/python2.7/site-packages/IPython/core/magics/execution.pyc in debug(self, line, cell)
331
332 if not (args.breakpoint or args.statement or cell):
--> 333 self._debug_post_mortem()
334 else:
335 code = "\n".join(args.statement)
/home/fperez/usr/lib/python2.7/site-packages/IPython/core/magics/execution.pyc in _debug_post_mortem(self)
339
340 def _debug_post_mortem(self):
--> 341 self.shell.debugger(force=True)
342
343 def _debug_exec(self, code, breakpoint):
/home/fperez/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in debugger(self, force)
920
921 with self.readline_no_record:
--> 922 pm()
923
924 #-------------------------------------------------------------------------
/home/fperez/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in <lambda>()
917 else:
918 # fallback to our internal debugger
--> 919 pm = lambda : self.InteractiveTB.debugger(force=True)
920
921 with self.readline_no_record:
/home/fperez/usr/lib/python2.7/site-packages/IPython/core/ultratb.pyc in debugger(self, force)
1007 etb = etb.tb_next
1008 self.pdb.botframe = etb.tb_frame
-> 1009 self.pdb.interaction(self.tb.tb_frame, self.tb)
1010
1011 if hasattr(self,'tb'):
/home/fperez/usr/lib/python2.7/site-packages/IPython/core/debugger.pyc in interaction(self, frame, traceback)
264 def interaction(self, frame, traceback):
265 self.shell.set_completer_frame(frame)
--> 266 OldPdb.interaction(self, frame, traceback)
267
268 def new_do_up(self, arg):
/usr/lib/python2.7/pdb.pyc in interaction(self, frame, traceback)
208 self.setup(frame, traceback)
209 self.print_stack_entry(self.stack[self.curindex])
--> 210 self.cmdloop()
211 self.forget()
212
/usr/lib/python2.7/cmd.pyc in cmdloop(self, intro)
128 if self.use_rawinput:
129 try:
--> 130 line = raw_input(self.prompt)
131 except EOFError:
132 line = 'EOF'
/home/fperez/usr/lib/python2.7/site-packages/IPython/kernel/zmq/ipkernel.pyc in <lambda>(prompt)
352 # raw_input in the user namespace.
353 if content.get('allow_stdin', False):
--> 354 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
355 else:
356 raw_input = lambda prompt='' : self._no_raw_input()
/home/fperez/usr/lib/python2.7/site-packages/IPython/kernel/zmq/ipkernel.pyc in _raw_input(self, prompt, ident, parent)
764 while True:
765 try:
--> 766 ident, reply = self.session.recv(self.stdin_socket, 0)
767 except Exception:
768 self.log.warn("Invalid Message:", exc_info=True)
/home/fperez/usr/lib/python2.7/site-packages/IPython/kernel/zmq/session.pyc in recv(self, socket, mode, content, copy)
655 socket = socket.socket
656 try:
--> 657 msg_list = socket.recv_multipart(mode, copy=copy)
658 except zmq.ZMQError as e:
659 if e.errno == zmq.EAGAIN:
/usr/lib/python2.7/dist-packages/zmq/core/pysocket.pyc in recv_multipart(self, flags, copy, track)
208
209 """
--> 210 parts = [self.recv(flags, copy=copy, track=track)]
211 # have first part already, only loop while more to receive
212 while self.getsockopt(zmq.RCVMORE):
/usr/lib/python2.7/dist-packages/zmq/core/socket.so in zmq.core.socket.Socket.recv (zmq/core/socket.c:5643)()
/usr/lib/python2.7/dist-packages/zmq/core/socket.so in zmq.core.socket.Socket.recv (zmq/core/socket.c:5465)()
/usr/lib/python2.7/dist-packages/zmq/core/socket.so in zmq.core.socket._recv_copy (zmq/core/socket.c:1688)()
/usr/lib/python2.7/dist-packages/zmq/core/error.so in zmq.core.error.ZMQError.__init__ (zmq/core/error.c:1059)()
KeyboardInterrupt:
|
EOFError
|
def open(self, kernel_id):
self.kernel_id = cast_unicode(kernel_id, "ascii")
self.session = Session(config=self.config)
self.save_on_message = self.on_message
self.on_message = self.on_first_message
|
def open(self, kernel_id):
self.kernel_id = kernel_id.decode("ascii")
self.session = Session(config=self.config)
self.save_on_message = self.on_message
self.on_message = self.on_first_message
|
https://github.com/ipython/ipython/issues/3494
|
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-1-9b8a430d8199> in <module>()
----> 1 a = input()
/home/thomas/Code/virtualenvs/ipy-3/lib/python3.3/site-packages/ipython-1.0.dev-py3.3.egg/IPython/kernel/zmq/ipkernel.py in <lambda>(prompt)
353 # raw_input in the user namespace.
354 if content.get('allow_stdin', False):
--> 355 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
356 else:
357 raw_input = lambda prompt='' : self._no_raw_input()
/home/thomas/Code/virtualenvs/ipy-3/lib/python3.3/site-packages/ipython-1.0.dev-py3.3.egg/IPython/kernel/zmq/ipkernel.py in _raw_input(self, prompt, ident, parent)
765 while True:
766 try:
--> 767 ident, reply = self.session.recv(self.stdin_socket, 0)
768 except Exception:
769 self.log.warn("Invalid Message:", exc_info=True)
/home/thomas/Code/virtualenvs/ipy-3/lib/python3.3/site-packages/ipython-1.0.dev-py3.3.egg/IPython/kernel/zmq/session.py in recv(self, socket, mode, content, copy)
657 socket = socket.socket
658 try:
--> 659 msg_list = socket.recv_multipart(mode, copy=copy)
660 except zmq.ZMQError as e:
661 if e.errno == zmq.EAGAIN:
/usr/lib/python3/dist-packages/zmq/core/pysocket.py in recv_multipart(self, flags, copy, track)
208
209 """
--> 210 parts = [self.recv(flags, copy=copy, track=track)]
211 # have first part already, only loop while more to receive
212 while self.getsockopt(zmq.RCVMORE):
/usr/lib/python3/dist-packages/zmq/core/socket.cpython-33m-i386-linux-gnu.so in zmq.core.socket.Socket.recv (zmq/core/socket.c:5643)()
/usr/lib/python3/dist-packages/zmq/core/socket.cpython-33m-i386-linux-gnu.so in zmq.core.socket.Socket.recv (zmq/core/socket.c:5465)()
/usr/lib/python3/dist-packages/zmq/core/socket.cpython-33m-i386-linux-gnu.so in zmq.core.socket._recv_copy (zmq/core/socket.c:1688)()
/usr/lib/python3/dist-packages/zmq/core/error.cpython-33m-i386-linux-gnu.so in zmq.core.error.ZMQError.__init__ (zmq/core/error.c:1059)()
KeyboardInterrupt:
|
zmq.ZMQError
|
def _inject_cookie_message(self, msg):
"""Inject the first message, which is the document cookie,
for authentication."""
if not PY3 and isinstance(msg, unicode):
# Cookie constructor doesn't accept unicode strings
# under Python 2.x for some reason
msg = msg.encode("utf8", "replace")
try:
identity, msg = msg.split(":", 1)
self.session.session = cast_unicode(identity, "ascii")
except Exception:
logging.error(
"First ws message didn't have the form 'identity:[cookie]' - %r", msg
)
try:
self.request._cookies = Cookie.SimpleCookie(msg)
except:
self.log.warn("couldn't parse cookie string: %s", msg, exc_info=True)
|
def _inject_cookie_message(self, msg):
"""Inject the first message, which is the document cookie,
for authentication."""
if not PY3 and isinstance(msg, unicode):
# Cookie constructor doesn't accept unicode strings
# under Python 2.x for some reason
msg = msg.encode("utf8", "replace")
try:
identity, msg = msg.split(":", 1)
self.session.session = identity.decode("ascii")
except Exception:
logging.error(
"First ws message didn't have the form 'identity:[cookie]' - %r", msg
)
try:
self.request._cookies = Cookie.SimpleCookie(msg)
except:
self.log.warn("couldn't parse cookie string: %s", msg, exc_info=True)
|
https://github.com/ipython/ipython/issues/3494
|
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-1-9b8a430d8199> in <module>()
----> 1 a = input()
/home/thomas/Code/virtualenvs/ipy-3/lib/python3.3/site-packages/ipython-1.0.dev-py3.3.egg/IPython/kernel/zmq/ipkernel.py in <lambda>(prompt)
353 # raw_input in the user namespace.
354 if content.get('allow_stdin', False):
--> 355 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
356 else:
357 raw_input = lambda prompt='' : self._no_raw_input()
/home/thomas/Code/virtualenvs/ipy-3/lib/python3.3/site-packages/ipython-1.0.dev-py3.3.egg/IPython/kernel/zmq/ipkernel.py in _raw_input(self, prompt, ident, parent)
765 while True:
766 try:
--> 767 ident, reply = self.session.recv(self.stdin_socket, 0)
768 except Exception:
769 self.log.warn("Invalid Message:", exc_info=True)
/home/thomas/Code/virtualenvs/ipy-3/lib/python3.3/site-packages/ipython-1.0.dev-py3.3.egg/IPython/kernel/zmq/session.py in recv(self, socket, mode, content, copy)
657 socket = socket.socket
658 try:
--> 659 msg_list = socket.recv_multipart(mode, copy=copy)
660 except zmq.ZMQError as e:
661 if e.errno == zmq.EAGAIN:
/usr/lib/python3/dist-packages/zmq/core/pysocket.py in recv_multipart(self, flags, copy, track)
208
209 """
--> 210 parts = [self.recv(flags, copy=copy, track=track)]
211 # have first part already, only loop while more to receive
212 while self.getsockopt(zmq.RCVMORE):
/usr/lib/python3/dist-packages/zmq/core/socket.cpython-33m-i386-linux-gnu.so in zmq.core.socket.Socket.recv (zmq/core/socket.c:5643)()
/usr/lib/python3/dist-packages/zmq/core/socket.cpython-33m-i386-linux-gnu.so in zmq.core.socket.Socket.recv (zmq/core/socket.c:5465)()
/usr/lib/python3/dist-packages/zmq/core/socket.cpython-33m-i386-linux-gnu.so in zmq.core.socket._recv_copy (zmq/core/socket.c:1688)()
/usr/lib/python3/dist-packages/zmq/core/error.cpython-33m-i386-linux-gnu.so in zmq.core.error.ZMQError.__init__ (zmq/core/error.c:1059)()
KeyboardInterrupt:
|
zmq.ZMQError
|
def open(self, kernel_id):
self.kernel_id = kernel_id.decode("ascii")
self.session = Session(config=self.config)
self.save_on_message = self.on_message
self.on_message = self.on_first_message
|
def open(self, kernel_id):
self.kernel_id = kernel_id.decode("ascii")
self.session = Session(parent=self)
self.save_on_message = self.on_message
self.on_message = self.on_first_message
|
https://github.com/ipython/ipython/issues/3502
|
ERROR:root:Uncaught exception in /kernels/3c8b14ec-662f-4360-bc2a-4706c67f8513/shell
Traceback (most recent call last):
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 254, in wrapper
return callback(*args, **kwargs)
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/html/base/zmqhandlers.py", line 87, in open
self.session = Session(parent=self)
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/kernel/zmq/session.py", line 395, in __init__
super(Session, self).__init__(**kwargs)
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/config/configurable.py", line 88, in __init__
self.parent = parent
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/utils/traitlets.py", line 315, in __set__
new_value = self._validate(obj, value)
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/utils/traitlets.py", line 323, in _validate
return self.validate(obj, value)
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/utils/traitlets.py", line 809, in validate
self.error(obj, value)
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/utils/traitlets.py", line 646, in error
raise TraitError(e)
TraitError: The 'parent' trait of a Session instance must be a Configurable or None, but a value of class 'IPython.html.services.kernels.handlers.ShellHandler' (i.e. <IPython.html.services.kernels.handlers.ShellHandler object at 0x1088c0950>) was specified.
ERROR:root:Uncaught exception, closing connection.
Traceback (most recent call last):
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/iostream.py", line 304, in wrapper
callback(*args)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/httpserver.py", line 250, in _on_headers
self.request_callback(self._request)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/web.py", line 1362, in __call__
handler._execute(transforms, *args, **kwargs)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 120, in _execute
self.ws_connection.accept_connection()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 454, in accept_connection
self._accept_connection()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 496, in _accept_connection
self._receive_frame()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 525, in _receive_frame
self.stream.read_bytes(2, self._on_frame_start)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/iostream.py", line 180, in read_bytes
self._check_closed()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/iostream.py", line 535, in _check_closed
raise IOError("Stream is closed")
IOError: Stream is closed
ERROR:root:Exception in callback <zmq.eventloop.stack_context._StackContextWrapper object at 0x108671890>
Traceback (most recent call last):
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/zmq/eventloop/ioloop.py", line 418, in _run_callback
callback()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/iostream.py", line 304, in wrapper
callback(*args)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/httpserver.py", line 250, in _on_headers
self.request_callback(self._request)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/web.py", line 1362, in __call__
handler._execute(transforms, *args, **kwargs)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 120, in _execute
self.ws_connection.accept_connection()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 454, in accept_connection
self._accept_connection()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 496, in _accept_connection
self._receive_frame()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 525, in _receive_frame
self.stream.read_bytes(2, self._on_frame_start)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/iostream.py", line 180, in read_bytes
self._check_closed()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/iostream.py", line 535, in _check_closed
raise IOError("Stream is closed")
IOError: Stream is closed
ERROR:root:Uncaught exception in /kernels/3c8b14ec-662f-4360-bc2a-4706c67f8513/stdin
Traceback (most recent call last):
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 254, in wrapper
return callback(*args, **kwargs)
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/html/base/zmqhandlers.py", line 87, in open
self.session = Session(parent=self)
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/kernel/zmq/session.py", line 395, in __init__
super(Session, self).__init__(**kwargs)
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/config/configurable.py", line 88, in __init__
self.parent = parent
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/utils/traitlets.py", line 315, in __set__
new_value = self._validate(obj, value)
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/utils/traitlets.py", line 323, in _validate
return self.validate(obj, value)
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/utils/traitlets.py", line 809, in validate
self.error(obj, value)
File "/Users/bgranger/Documents/Computing/IPython/code/ipython/IPython/utils/traitlets.py", line 646, in error
raise TraitError(e)
TraitError: The 'parent' trait of a Session instance must be a Configurable or None, but a value of class 'IPython.html.services.kernels.handlers.StdinHandler' (i.e. <IPython.html.services.kernels.handlers.StdinHandler object at 0x1085d7510>) was specified.
ERROR:root:Uncaught exception, closing connection.
Traceback (most recent call last):
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/iostream.py", line 304, in wrapper
callback(*args)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/httpserver.py", line 250, in _on_headers
self.request_callback(self._request)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/web.py", line 1362, in __call__
handler._execute(transforms, *args, **kwargs)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 120, in _execute
self.ws_connection.accept_connection()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 454, in accept_connection
self._accept_connection()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 496, in _accept_connection
self._receive_frame()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 525, in _receive_frame
self.stream.read_bytes(2, self._on_frame_start)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/iostream.py", line 180, in read_bytes
self._check_closed()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/iostream.py", line 535, in _check_closed
raise IOError("Stream is closed")
IOError: Stream is closed
ERROR:root:Exception in callback <zmq.eventloop.stack_context._StackContextWrapper object at 0x108671890>
Traceback (most recent call last):
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/zmq/eventloop/ioloop.py", line 418, in _run_callback
callback()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/iostream.py", line 304, in wrapper
callback(*args)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/httpserver.py", line 250, in _on_headers
self.request_callback(self._request)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/web.py", line 1362, in __call__
handler._execute(transforms, *args, **kwargs)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 120, in _execute
self.ws_connection.accept_connection()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 454, in accept_connection
self._accept_connection()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 496, in _accept_connection
self._receive_frame()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/websocket.py", line 525, in _receive_frame
self.stream.read_bytes(2, self._on_frame_start)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/iostream.py", line 180, in read_bytes
self._check_closed()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/tornado/iostream.py", line 535, in _check_closed
raise IOError("Stream is closed")
IOError: Stream is closed
|
TraitError
|
def _handle_kernel_died(self, kernel_id):
"""notice that a kernel died"""
self.log.warn("Kernel %s died, removing from map.", kernel_id)
self.delete_mapping_for_kernel(kernel_id)
self.remove_kernel(kernel_id)
|
def _handle_kernel_died(self, kernel_id):
"""notice that a kernel died"""
self.log.warn("Kernel %s died, removing from map.", kernel_id)
self.delete_mapping_for_kernel(kernel_id)
self.remove_kernel(kernel_id, now=True)
|
https://github.com/ipython/ipython/issues/3474
|
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/IPython/kernel/restarter.py", line 85, in _fire_callbacks
callback()
File "/usr/local/lib/python2.7/dist-packages/IPython/frontend/html/notebook/services/kernels/kernelmanager.py", line 92, in <lambda>
lambda : self._handle_kernel_died(kernel_id),
File "/usr/local/lib/python2.7/dist-packages/IPython/frontend/html/notebook/services/kernels/kernelmanager.py", line 71, in _handle_kernel_died
self.remove_kernel(kernel_id, now=True)
TypeError: remove_kernel() got an unexpected keyword argument 'now'
|
TypeError
|
def check_startup_dir(self):
if not os.path.isdir(self.startup_dir):
os.mkdir(self.startup_dir)
readme = os.path.join(self.startup_dir, "README")
src = os.path.join(get_ipython_package_dir(), "config", "profile", "README_STARTUP")
if not os.path.exists(src):
self.log.warn(
"Could not copy README_STARTUP to startup dir. Source file %s does not exist."
% src
)
if os.path.exists(src) and not os.path.exists(readme):
shutil.copy(src, readme)
|
def check_startup_dir(self):
if not os.path.isdir(self.startup_dir):
os.mkdir(self.startup_dir)
readme = os.path.join(self.startup_dir, "README")
src = os.path.join(get_ipython_package_dir(), "config", "profile", "README_STARTUP")
if not os.path.exists(readme):
shutil.copy(src, readme)
|
https://github.com/ipython/ipython/issues/2563
|
Traceback (most recent call last):
[--snip--]
File "IPython\core\profiledir.pyc", line 106, in check_startup_dir
File "shutil.pyc", line 116, in copy
File "shutil.pyc", line 81, in copyfile
IOError: [Errno 2] No such file or directory: u'C:\\Documents and Settings\\User\\My Documents\\sofware\\dist\\library.zip\\IPython\\config\\profile\\README_STARTUP'
|
IOError
|
def __init__(self, parent, lexer=None):
super(PygmentsHighlighter, self).__init__(parent)
self._document = self.document()
self._formatter = HtmlFormatter(nowrap=True)
self._lexer = lexer if lexer else PythonLexer()
self.set_style("default")
|
def __init__(self, parent, lexer=None):
super(PygmentsHighlighter, self).__init__(parent)
self._document = QtGui.QTextDocument()
self._formatter = HtmlFormatter(nowrap=True)
self._lexer = lexer if lexer else PythonLexer()
self.set_style("default")
|
https://github.com/ipython/ipython/issues/3084
|
if 1:
print 1
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/IPython/frontend/qt/console/frontend_widget.py", line 59, in highlightBlock
super(FrontendHighlighter, self).highlightBlock(string)
File "/usr/lib/python2.7/dist-packages/IPython/frontend/qt/console/pygments_highlighter.py", line 109, in highlightBlock
self._lexer._saved_state_stack = prev_data.syntax_stack
AttributeError: 'QTextBlockUserData' object has no attribute 'syntax_stack'
|
AttributeError
|
def launch_kernel(
cmd,
stdin=None,
stdout=None,
stderr=None,
independent=False,
cwd=None,
ipython_kernel=True,
**kw,
):
"""Launches a localhost kernel, binding to the specified ports.
Parameters
----------
cmd : Popen list,
A string of Python code that imports and executes a kernel entry point.
stdin, stdout, stderr : optional (default None)
Standards streams, as defined in subprocess.Popen.
independent : bool, optional (default False)
If set, the kernel process is guaranteed to survive if this process
dies. If not set, an effort is made to ensure that the kernel is killed
when this process dies. Note that in this case it is still good practice
to kill kernels manually before exiting.
cwd : path, optional
The working dir of the kernel process (default: cwd of this process).
ipython_kernel : bool, optional
Whether the kernel is an official IPython one,
and should get a bit of special treatment.
Returns
-------
Popen instance for the kernel subprocess
"""
# Popen will fail (sometimes with a deadlock) if stdin, stdout, and stderr
# are invalid. Unfortunately, there is in general no way to detect whether
# they are valid. The following two blocks redirect them to (temporary)
# pipes in certain important cases.
# If this process has been backgrounded, our stdin is invalid. Since there
# is no compelling reason for the kernel to inherit our stdin anyway, we'll
# place this one safe and always redirect.
redirect_in = True
_stdin = PIPE if stdin is None else stdin
# If this process in running on pythonw, we know that stdin, stdout, and
# stderr are all invalid.
redirect_out = sys.executable.endswith("pythonw.exe")
if redirect_out:
_stdout = PIPE if stdout is None else stdout
_stderr = PIPE if stderr is None else stderr
else:
_stdout, _stderr = stdout, stderr
# Spawn a kernel.
if sys.platform == "win32":
if cwd:
# Popen on Python 2 on Windows cannot handle unicode cwd.
cwd = cast_bytes_py2(cwd, sys.getfilesystemencoding() or "ascii")
from IPython.kernel.zmq.parentpoller import ParentPollerWindows
# Create a Win32 event for interrupting the kernel.
interrupt_event = ParentPollerWindows.create_interrupt_event()
if ipython_kernel:
cmd += ["--interrupt=%i" % interrupt_event]
# If the kernel is running on pythonw and stdout/stderr are not been
# re-directed, it will crash when more than 4KB of data is written to
# stdout or stderr. This is a bug that has been with Python for a very
# long time; see http://bugs.python.org/issue706263.
# A cleaner solution to this problem would be to pass os.devnull to
# Popen directly. Unfortunately, that does not work.
if cmd[0].endswith("pythonw.exe"):
if stdout is None:
cmd.append("--no-stdout")
if stderr is None:
cmd.append("--no-stderr")
# Launch the kernel process.
if independent:
proc = Popen(
cmd,
creationflags=512, # CREATE_NEW_PROCESS_GROUP
stdin=_stdin,
stdout=_stdout,
stderr=_stderr,
env=os.environ,
)
else:
if ipython_kernel:
try:
from _winapi import (
DuplicateHandle,
GetCurrentProcess,
DUPLICATE_SAME_ACCESS,
)
except:
from _subprocess import (
DuplicateHandle,
GetCurrentProcess,
DUPLICATE_SAME_ACCESS,
)
pid = GetCurrentProcess()
handle = DuplicateHandle(
pid,
pid,
pid,
0,
True, # Inheritable by new processes.
DUPLICATE_SAME_ACCESS,
)
cmd += ["--parent=%i" % handle]
proc = Popen(
cmd,
stdin=_stdin,
stdout=_stdout,
stderr=_stderr,
cwd=cwd,
env=os.environ,
)
# Attach the interrupt event to the Popen objet so it can be used later.
proc.win32_interrupt_event = interrupt_event
else:
if independent:
proc = Popen(
cmd,
preexec_fn=lambda: os.setsid(),
stdin=_stdin,
stdout=_stdout,
stderr=_stderr,
cwd=cwd,
env=os.environ,
)
else:
if ipython_kernel:
cmd += ["--parent=1"]
proc = Popen(
cmd,
stdin=_stdin,
stdout=_stdout,
stderr=_stderr,
cwd=cwd,
env=os.environ,
)
# Clean up pipes created to work around Popen bug.
if redirect_in:
if stdin is None:
proc.stdin.close()
if redirect_out:
if stdout is None:
proc.stdout.close()
if stderr is None:
proc.stderr.close()
return proc
|
def launch_kernel(
cmd,
stdin=None,
stdout=None,
stderr=None,
independent=False,
cwd=None,
ipython_kernel=True,
**kw,
):
"""Launches a localhost kernel, binding to the specified ports.
Parameters
----------
cmd : Popen list,
A string of Python code that imports and executes a kernel entry point.
stdin, stdout, stderr : optional (default None)
Standards streams, as defined in subprocess.Popen.
independent : bool, optional (default False)
If set, the kernel process is guaranteed to survive if this process
dies. If not set, an effort is made to ensure that the kernel is killed
when this process dies. Note that in this case it is still good practice
to kill kernels manually before exiting.
cwd : path, optional
The working dir of the kernel process (default: cwd of this process).
ipython_kernel : bool, optional
Whether the kernel is an official IPython one,
and should get a bit of special treatment.
Returns
-------
Popen instance for the kernel subprocess
"""
# Popen will fail (sometimes with a deadlock) if stdin, stdout, and stderr
# are invalid. Unfortunately, there is in general no way to detect whether
# they are valid. The following two blocks redirect them to (temporary)
# pipes in certain important cases.
# If this process has been backgrounded, our stdin is invalid. Since there
# is no compelling reason for the kernel to inherit our stdin anyway, we'll
# place this one safe and always redirect.
redirect_in = True
_stdin = PIPE if stdin is None else stdin
# If this process in running on pythonw, we know that stdin, stdout, and
# stderr are all invalid.
redirect_out = sys.executable.endswith("pythonw.exe")
if redirect_out:
_stdout = PIPE if stdout is None else stdout
_stderr = PIPE if stderr is None else stderr
else:
_stdout, _stderr = stdout, stderr
# Spawn a kernel.
if sys.platform == "win32":
from IPython.kernel.zmq.parentpoller import ParentPollerWindows
# Create a Win32 event for interrupting the kernel.
interrupt_event = ParentPollerWindows.create_interrupt_event()
if ipython_kernel:
cmd += ["--interrupt=%i" % interrupt_event]
# If the kernel is running on pythonw and stdout/stderr are not been
# re-directed, it will crash when more than 4KB of data is written to
# stdout or stderr. This is a bug that has been with Python for a very
# long time; see http://bugs.python.org/issue706263.
# A cleaner solution to this problem would be to pass os.devnull to
# Popen directly. Unfortunately, that does not work.
if cmd[0].endswith("pythonw.exe"):
if stdout is None:
cmd.append("--no-stdout")
if stderr is None:
cmd.append("--no-stderr")
# Launch the kernel process.
if independent:
proc = Popen(
cmd,
creationflags=512, # CREATE_NEW_PROCESS_GROUP
stdin=_stdin,
stdout=_stdout,
stderr=_stderr,
env=os.environ,
)
else:
if ipython_kernel:
try:
from _winapi import (
DuplicateHandle,
GetCurrentProcess,
DUPLICATE_SAME_ACCESS,
)
except:
from _subprocess import (
DuplicateHandle,
GetCurrentProcess,
DUPLICATE_SAME_ACCESS,
)
pid = GetCurrentProcess()
handle = DuplicateHandle(
pid,
pid,
pid,
0,
True, # Inheritable by new processes.
DUPLICATE_SAME_ACCESS,
)
cmd += ["--parent=%i" % handle]
proc = Popen(
cmd,
stdin=_stdin,
stdout=_stdout,
stderr=_stderr,
cwd=cwd,
env=os.environ,
)
# Attach the interrupt event to the Popen objet so it can be used later.
proc.win32_interrupt_event = interrupt_event
else:
if independent:
proc = Popen(
cmd,
preexec_fn=lambda: os.setsid(),
stdin=_stdin,
stdout=_stdout,
stderr=_stderr,
cwd=cwd,
env=os.environ,
)
else:
if ipython_kernel:
cmd += ["--parent=1"]
proc = Popen(
cmd,
stdin=_stdin,
stdout=_stdout,
stderr=_stderr,
cwd=cwd,
env=os.environ,
)
# Clean up pipes created to work around Popen bug.
if redirect_in:
if stdin is None:
proc.stdin.close()
if redirect_out:
if stdout is None:
proc.stdout.close()
if stderr is None:
proc.stderr.close()
return proc
|
https://github.com/ipython/ipython/issues/3039
|
C:\python\ipydevel\notebooks\åäö> ipython notebook
[NotebookApp] Using existing profile dir: u'C:\\Users\\jstenar\\.ipython\\profile_default'
[NotebookApp] Serving notebooks from local directory: C:\python\ipydevel\notebooks\åäö
[NotebookApp] The IPython Notebook is running at: http://127.0.0.1:8888/
[NotebookApp] Use Control-C to stop this server and shut down all kernels.
[NotebookApp] Using MathJax from CDN: http://cdn.mathjax.org/mathjax/latest/MathJax.js
ERROR:root:Uncaught exception POST /kernels?notebook=b6abbe73-c225-4182-8b86-4c4094480d4d (127.0.0.1)
HTTPRequest(protocol='http', host='127.0.0.1:8888', method='POST', uri='/kernels?notebook=b6abbe73-c225-4182-8b86-4c4094480d4d', version='HTTP/1.1', remote_ip='127.0.0.1', body='', headers={'Origin': 'http://127.0.0.1:8888', 'Content-Length': '0', 'Accept-Language': 'sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4', 'Accept-Encoding': 'gzip,deflate,sdch', 'Host': '127.0.0.1:8888', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Connection': 'keep-alive', 'X-Requested-With': 'XMLHttpRequest', 'Referer': 'http://127.0.0.1:8888/b6abbe73-c225-4182-8b86-4c4094480d4d'})
Traceback (most recent call last):
File "C:\python27\lib\site-packages\tornado\web.py", line 1021, in _execute
getattr(self, self.request.method.lower())(*args, **kwargs)
File "C:\python27\lib\site-packages\tornado\web.py", line 1794, in wrapper
return method(self, *args, **kwargs)
File "C:\python27\lib\site-packages\ipython-1.0.dev-py2.7.egg\IPython\frontend\html\notebook\handlers.py", line 352, in post
kernel_id = km.start_kernel(notebook_id, cwd=nbm.notebook_dir)
File "C:\python27\lib\site-packages\ipython-1.0.dev-py2.7.egg\IPython\frontend\html\notebook\kernelmanager.py", line 85, in start_kernel
kernel_id = super(MappingKernelManager, self).start_kernel(**kwargs)
File "C:\python27\lib\site-packages\ipython-1.0.dev-py2.7.egg\IPython\kernel\multikernelmanager.py", line 98, in start_kernel
km.start_kernel(**kwargs)
File "C:\python27\lib\site-packages\ipython-1.0.dev-py2.7.egg\IPython\kernel\kernelmanager.py", line 950, in start_kernel
**kw)
File "C:\python27\lib\site-packages\ipython-1.0.dev-py2.7.egg\IPython\kernel\kernelmanager.py", line 919, in _launch_kernel
return launch_kernel(kernel_cmd, **kw)
File "C:\python27\lib\site-packages\ipython-1.0.dev-py2.7.egg\IPython\kernel\launcher.py", line 227, in launch_kernel
stdin=_stdin, stdout=_stdout, stderr=_stderr, cwd=cwd, env=os.environ)
File "C:\python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\python27\lib\subprocess.py", line 893, in _execute_child
startupinfo)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 29-31: ordinal not in range(128)
ERROR:root:500 POST /kernels?notebook=b6abbe73-c225-4182-8b86-4c4094480d4d (127.0.0.1) 13.00ms
|
UnicodeEncodeError
|
def osx_clipboard_get():
"""Get the clipboard's text on OS X."""
p = subprocess.Popen(["pbpaste", "-Prefer", "ascii"], stdout=subprocess.PIPE)
text, stderr = p.communicate()
# Text comes in with old Mac \r line endings. Change them to \n.
text = text.replace(b"\r", b"\n")
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
return text
|
def osx_clipboard_get():
"""Get the clipboard's text on OS X."""
p = subprocess.Popen(["pbpaste", "-Prefer", "ascii"], stdout=subprocess.PIPE)
text, stderr = p.communicate()
# Text comes in with old Mac \r line endings. Change them to \n.
text = text.replace("\r", "\n")
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
return text
|
https://github.com/ipython/ipython/issues/2637
|
In [1]: %paste
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-86b9186405a3> in <module>()
----> 1 get_ipython().magic('paste')
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/core/interactiveshell.py in magic(self, arg_s)
2135 magic_name, _, magic_arg_s = arg_s.partition(' ')
2136 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2137 return self.run_line_magic(magic_name, magic_arg_s)
2138
2139 #-------------------------------------------------------------------------
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
2061 args.append(sys._getframe(stack_depth).f_locals)
2062 with self.builtin_trap:
-> 2063 result = fn(*args)
2064 return result
2065
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/frontend/terminal/interactiveshell.py in paste(self, parameter_s)
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/core/magic.py in <lambda>(f, *a, **k)
190 # but it's overkill for just that one bit of state.
191 def magic_deco(arg):
--> 192 call = lambda f, *a, **k: f(*a, **k)
193
194 if isinstance(arg, collections.Callable):
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/frontend/terminal/interactiveshell.py in paste(self, parameter_s)
270 return
271 try:
--> 272 block = self.shell.hooks.clipboard_get()
273 except TryNext as clipboard_exc:
274 message = getattr(clipboard_exc, 'args')
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/core/hooks.py in __call__(self, *args, **kw)
136 #print "prio",prio,"cmd",cmd #dbg
137 try:
--> 138 return cmd(*args, **kw)
139 except TryNext as exc:
140 last_exc = exc
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/core/hooks.py in clipboard_get(self)
227 for func in chain:
228 dispatcher.add(func)
--> 229 text = dispatcher()
230 return text
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/core/hooks.py in __call__(self, *args, **kw)
136 #print "prio",prio,"cmd",cmd #dbg
137 try:
--> 138 return cmd(*args, **kw)
139 except TryNext as exc:
140 last_exc = exc
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/lib/clipboard.py in osx_clipboard_get()
31 text, stderr = p.communicate()
32 # Text comes in with old Mac \r line endings. Change them to \n.
---> 33 text = text.replace('\r', '\n')
34 return text
35
TypeError: expected bytes, bytearray or buffer compatible object
|
TypeError
|
def osx_clipboard_get():
"""Get the clipboard's text on OS X."""
p = subprocess.Popen(["pbpaste", "-Prefer", "ascii"], stdout=subprocess.PIPE)
text, stderr = p.communicate()
# Text comes in with old Mac \r line endings. Change them to \n.
text = text.replace(b"\r", b"\n")
return text
|
def osx_clipboard_get():
"""Get the clipboard's text on OS X."""
p = subprocess.Popen(["pbpaste", "-Prefer", "ascii"], stdout=subprocess.PIPE)
text, stderr = p.communicate()
# Text comes in with old Mac \r line endings. Change them to \n.
text = text.replace("\r", "\n")
return text
|
https://github.com/ipython/ipython/issues/2637
|
In [1]: %paste
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-86b9186405a3> in <module>()
----> 1 get_ipython().magic('paste')
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/core/interactiveshell.py in magic(self, arg_s)
2135 magic_name, _, magic_arg_s = arg_s.partition(' ')
2136 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2137 return self.run_line_magic(magic_name, magic_arg_s)
2138
2139 #-------------------------------------------------------------------------
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
2061 args.append(sys._getframe(stack_depth).f_locals)
2062 with self.builtin_trap:
-> 2063 result = fn(*args)
2064 return result
2065
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/frontend/terminal/interactiveshell.py in paste(self, parameter_s)
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/core/magic.py in <lambda>(f, *a, **k)
190 # but it's overkill for just that one bit of state.
191 def magic_deco(arg):
--> 192 call = lambda f, *a, **k: f(*a, **k)
193
194 if isinstance(arg, collections.Callable):
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/frontend/terminal/interactiveshell.py in paste(self, parameter_s)
270 return
271 try:
--> 272 block = self.shell.hooks.clipboard_get()
273 except TryNext as clipboard_exc:
274 message = getattr(clipboard_exc, 'args')
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/core/hooks.py in __call__(self, *args, **kw)
136 #print "prio",prio,"cmd",cmd #dbg
137 try:
--> 138 return cmd(*args, **kw)
139 except TryNext as exc:
140 last_exc = exc
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/core/hooks.py in clipboard_get(self)
227 for func in chain:
228 dispatcher.add(func)
--> 229 text = dispatcher()
230 return text
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/core/hooks.py in __call__(self, *args, **kw)
136 #print "prio",prio,"cmd",cmd #dbg
137 try:
--> 138 return cmd(*args, **kw)
139 except TryNext as exc:
140 last_exc = exc
/sw/lib/python3.3/site-packages/ipython-0.13.1-py3.3.egg/IPython/lib/clipboard.py in osx_clipboard_get()
31 text, stderr = p.communicate()
32 # Text comes in with old Mac \r line endings. Change them to \n.
---> 33 text = text.replace('\r', '\n')
34 return text
35
TypeError: expected bytes, bytearray or buffer compatible object
|
TypeError
|
def __init__(self, session, pub_socket, name):
self.encoding = "UTF-8"
self.session = session
self.pub_socket = pub_socket
self.name = name
self.parent_header = {}
self._new_buffer()
|
def __init__(self, session, pub_socket, name):
self.session = session
self.pub_socket = pub_socket
self.name = name
self.parent_header = {}
self._new_buffer()
|
https://github.com/ipython/ipython/issues/2220
|
% ./ipython.py console
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
Type "copyright", "credits" or "license" for more information.
IPython 0.14.dev -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing kernel-8616.json
In [1]: import sys
In [2]: sys.stdout.encoding
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-18fba92f6a6c> in <module>()
----> 1 sys.stdout.encoding
AttributeError: 'OutStream' object has no attribute 'encoding'
|
AttributeError
|
def write(self, string):
if self.pub_socket is None:
raise ValueError("I/O operation on closed file")
else:
# Make sure that we're handling unicode
if not isinstance(string, unicode):
string = string.decode(self.encoding, "replace")
self._buffer.write(string)
current_time = time.time()
if self._start <= 0:
self._start = current_time
elif current_time - self._start > self.flush_interval:
self.flush()
|
def write(self, string):
if self.pub_socket is None:
raise ValueError("I/O operation on closed file")
else:
# Make sure that we're handling unicode
if not isinstance(string, unicode):
enc = encoding.DEFAULT_ENCODING
string = string.decode(enc, "replace")
self._buffer.write(string)
current_time = time.time()
if self._start <= 0:
self._start = current_time
elif current_time - self._start > self.flush_interval:
self.flush()
|
https://github.com/ipython/ipython/issues/2220
|
% ./ipython.py console
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
Type "copyright", "credits" or "license" for more information.
IPython 0.14.dev -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing kernel-8616.json
In [1]: import sys
In [2]: sys.stdout.encoding
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-18fba92f6a6c> in <module>()
----> 1 sys.stdout.encoding
AttributeError: 'OutStream' object has no attribute 'encoding'
|
AttributeError
|
def __init__(self, profile="default", hist_file="", config=None, **traits):
"""Create a new history accessor.
Parameters
----------
profile : str
The name of the profile from which to open history.
hist_file : str
Path to an SQLite history database stored by IPython. If specified,
hist_file overrides profile.
config :
Config object. hist_file can also be set through this.
"""
# We need a pointer back to the shell for various tasks.
super(HistoryAccessor, self).__init__(config=config, **traits)
# defer setting hist_file from kwarg until after init,
# otherwise the default kwarg value would clobber any value
# set by config
if hist_file:
self.hist_file = hist_file
if self.hist_file == "":
# No one has set the hist_file, yet.
self.hist_file = self._get_hist_file_name(profile)
if sqlite3 is None and self.enabled:
warn("IPython History requires SQLite, your history will not be saved\n")
self.enabled = False
self.init_db()
|
def __init__(self, profile="default", hist_file="", config=None, **traits):
"""Create a new history accessor.
Parameters
----------
profile : str
The name of the profile from which to open history.
hist_file : str
Path to an SQLite history database stored by IPython. If specified,
hist_file overrides profile.
config :
Config object. hist_file can also be set through this.
"""
# We need a pointer back to the shell for various tasks.
super(HistoryAccessor, self).__init__(config=config, **traits)
# defer setting hist_file from kwarg until after init,
# otherwise the default kwarg value would clobber any value
# set by config
if hist_file:
self.hist_file = hist_file
if self.hist_file == "":
# No one has set the hist_file, yet.
self.hist_file = self._get_hist_file_name(profile)
if sqlite3 is None and self.enabled:
warn("IPython History requires SQLite, your history will not be saved\n")
self.enabled = False
if sqlite3 is not None:
DatabaseError = sqlite3.DatabaseError
else:
DatabaseError = Exception
try:
self.init_db()
except DatabaseError:
if os.path.isfile(self.hist_file):
# Try to move the file out of the way
base, ext = os.path.splitext(self.hist_file)
newpath = base + "-corrupt" + ext
os.rename(self.hist_file, newpath)
print(
"ERROR! History file wasn't a valid SQLite database.",
"It was moved to %s" % newpath,
"and a new file created.",
)
self.init_db()
else:
# The hist_file is probably :memory: or something else.
raise
|
https://github.com/ipython/ipython/issues/2097
|
(master)dreamweaver[nbconvert]> ip
Traceback (most recent call last):
File "/home/fperez/usr/bin/ipython", line 7, in <module>
launch_new_instance()
File "/home/fperez/usr/lib/python2.7/site-packages/IPython/frontend/terminal/ipapp.py", line 388, in launch_new_instance
app.initialize()
File "<string>", line 2, in initialize
File "/home/fperez/usr/lib/python2.7/site-packages/IPython/config/application.py", line 84, in catch_config_error
return method(app, *args, **kwargs)
File "/home/fperez/usr/lib/python2.7/site-packages/IPython/frontend/terminal/ipapp.py", line 324, in initialize
self.init_shell()
File "/home/fperez/usr/lib/python2.7/site-packages/IPython/frontend/terminal/ipapp.py", line 340, in init_shell
ipython_dir=self.ipython_dir)
File "/home/fperez/usr/lib/python2.7/site-packages/IPython/config/configurable.py", line 318, in instance
inst = cls(*args, **kwargs)
File "/home/fperez/usr/lib/python2.7/site-packages/IPython/frontend/terminal/interactiveshell.py", line 360, in __init__
user_module=user_module, custom_exceptions=custom_exceptions
File "/home/fperez/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 481, in __init__
self.init_readline()
File "/home/fperez/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 1868, in init_readline
self.refill_readline_hist()
File "/home/fperez/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 1880, in refill_readline_hist
include_latest=True):
File "/home/fperez/usr/lib/python2.7/site-packages/IPython/core/history.py", line 252, in get_tail
(n,), raw=raw, output=output)
File "/home/fperez/usr/lib/python2.7/site-packages/IPython/core/history.py", line 197, in _run_sql
(toget, sqlfrom) + sql, params)
DatabaseError: database disk image is malformed
|
DatabaseError
|
def format_stack_entry(self, frame_lineno, lprefix=": ", context=3):
import repr
ret = []
Colors = self.color_scheme_table.active_colors
ColorsNormal = Colors.Normal
tpl_link = "%s%%s%s" % (Colors.filenameEm, ColorsNormal)
tpl_call = "%s%%s%s%%s%s" % (Colors.vName, Colors.valEm, ColorsNormal)
tpl_line = "%%s%s%%s %s%%s" % (Colors.lineno, ColorsNormal)
tpl_line_em = "%%s%s%%s %s%%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal)
frame, lineno = frame_lineno
return_value = ""
if "__return__" in frame.f_locals:
rv = frame.f_locals["__return__"]
# return_value += '->'
return_value += repr.repr(rv) + "\n"
ret.append(return_value)
# s = filename + '(' + `lineno` + ')'
filename = self.canonic(frame.f_code.co_filename)
link = tpl_link % py3compat.cast_unicode(filename)
if frame.f_code.co_name:
func = frame.f_code.co_name
else:
func = "<lambda>"
call = ""
if func != "?":
if "__args__" in frame.f_locals:
args = repr.repr(frame.f_locals["__args__"])
else:
args = "()"
call = tpl_call % (func, args)
# The level info should be generated in the same format pdb uses, to
# avoid breaking the pdbtrack functionality of python-mode in *emacs.
if frame is self.curframe:
ret.append("> ")
else:
ret.append(" ")
ret.append("%s(%s)%s\n" % (link, lineno, call))
start = lineno - 1 - context // 2
lines = ulinecache.getlines(filename)
start = max(start, 0)
start = min(start, len(lines) - context)
lines = lines[start : start + context]
for i, line in enumerate(lines):
show_arrow = start + 1 + i == lineno
linetpl = (frame is self.curframe or show_arrow) and tpl_line_em or tpl_line
ret.append(
self.__format_line(linetpl, filename, start + 1 + i, line, arrow=show_arrow)
)
return "".join(ret)
|
def format_stack_entry(self, frame_lineno, lprefix=": ", context=3):
import linecache, repr
ret = []
Colors = self.color_scheme_table.active_colors
ColorsNormal = Colors.Normal
tpl_link = "%s%%s%s" % (Colors.filenameEm, ColorsNormal)
tpl_call = "%s%%s%s%%s%s" % (Colors.vName, Colors.valEm, ColorsNormal)
tpl_line = "%%s%s%%s %s%%s" % (Colors.lineno, ColorsNormal)
tpl_line_em = "%%s%s%%s %s%%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal)
frame, lineno = frame_lineno
return_value = ""
if "__return__" in frame.f_locals:
rv = frame.f_locals["__return__"]
# return_value += '->'
return_value += repr.repr(rv) + "\n"
ret.append(return_value)
# s = filename + '(' + `lineno` + ')'
filename = self.canonic(frame.f_code.co_filename)
link = tpl_link % filename
if frame.f_code.co_name:
func = frame.f_code.co_name
else:
func = "<lambda>"
call = ""
if func != "?":
if "__args__" in frame.f_locals:
args = repr.repr(frame.f_locals["__args__"])
else:
args = "()"
call = tpl_call % (func, args)
# The level info should be generated in the same format pdb uses, to
# avoid breaking the pdbtrack functionality of python-mode in *emacs.
if frame is self.curframe:
ret.append("> ")
else:
ret.append(" ")
ret.append("%s(%s)%s\n" % (link, lineno, call))
start = lineno - 1 - context // 2
lines = linecache.getlines(filename)
start = max(start, 0)
start = min(start, len(lines) - context)
lines = lines[start : start + context]
for i, line in enumerate(lines):
show_arrow = start + 1 + i == lineno
linetpl = (frame is self.curframe or show_arrow) and tpl_line_em or tpl_line
ret.append(
self.__format_line(linetpl, filename, start + 1 + i, line, arrow=show_arrow)
)
return "".join(ret)
|
https://github.com/ipython/ipython/issues/1688
|
In [1]: %run err.py
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
C:\python\ipydevel\VENV\Py27\lib\site-packages\ipython-0.13.dev-py2.7.egg\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
166 else:
167 filename = fname
--> 168 exec compile(scripttext, filename, 'exec') in glob, loc
169 else:
170 def execfile(fname, *where):
C:\python\ipydevel\err.py in <module>()
5 b=2+4
6
----> 7 a()
C:\python\ipydevel\err.py in a()
2 def a():
3 a=1+2
----> 4 1/0
5 b=2+4
6
ZeroDivisionError: integer division or modulo by zero
|
ZeroDivisionError
|
def print_list_lines(self, filename, first, last):
"""The printing (as opposed to the parsing part of a 'list'
command."""
try:
Colors = self.color_scheme_table.active_colors
ColorsNormal = Colors.Normal
tpl_line = "%%s%s%%s %s%%s" % (Colors.lineno, ColorsNormal)
tpl_line_em = "%%s%s%%s %s%%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal)
src = []
if filename == "<string>" and hasattr(self, "_exec_filename"):
filename = self._exec_filename
for lineno in range(first, last + 1):
line = ulinecache.getline(filename, lineno)
if not line:
break
if lineno == self.curframe.f_lineno:
line = self.__format_line(
tpl_line_em, filename, lineno, line, arrow=True
)
else:
line = self.__format_line(tpl_line, filename, lineno, line, arrow=False)
src.append(line)
self.lineno = lineno
print("".join(src), file=io.stdout)
except KeyboardInterrupt:
pass
|
def print_list_lines(self, filename, first, last):
"""The printing (as opposed to the parsing part of a 'list'
command."""
try:
Colors = self.color_scheme_table.active_colors
ColorsNormal = Colors.Normal
tpl_line = "%%s%s%%s %s%%s" % (Colors.lineno, ColorsNormal)
tpl_line_em = "%%s%s%%s %s%%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal)
src = []
for lineno in range(first, last + 1):
line = linecache.getline(filename, lineno)
if not line:
break
if lineno == self.curframe.f_lineno:
line = self.__format_line(
tpl_line_em, filename, lineno, line, arrow=True
)
else:
line = self.__format_line(tpl_line, filename, lineno, line, arrow=False)
src.append(line)
self.lineno = lineno
print("".join(src), file=io.stdout)
except KeyboardInterrupt:
pass
|
https://github.com/ipython/ipython/issues/1688
|
In [1]: %run err.py
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
C:\python\ipydevel\VENV\Py27\lib\site-packages\ipython-0.13.dev-py2.7.egg\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
166 else:
167 filename = fname
--> 168 exec compile(scripttext, filename, 'exec') in glob, loc
169 else:
170 def execfile(fname, *where):
C:\python\ipydevel\err.py in <module>()
5 b=2+4
6
----> 7 a()
C:\python\ipydevel\err.py in a()
2 def a():
3 a=1+2
----> 4 1/0
5 b=2+4
6
ZeroDivisionError: integer division or modulo by zero
|
ZeroDivisionError
|
def getdoc(obj):
"""Stable wrapper around inspect.getdoc.
This can't crash because of attribute problems.
It also attempts to call a getdoc() method on the given object. This
allows objects which provide their docstrings via non-standard mechanisms
(like Pyro proxies) to still be inspected by ipython's ? system."""
# Allow objects to offer customized documentation via a getdoc method:
try:
ds = obj.getdoc()
except Exception:
pass
else:
# if we get extra info, we add it to the normal docstring.
if isinstance(ds, basestring):
return inspect.cleandoc(ds)
try:
docstr = inspect.getdoc(obj)
encoding = get_encoding(obj)
return py3compat.cast_unicode(docstr, encoding=encoding)
except Exception:
# Harden against an inspect failure, which can occur with
# SWIG-wrapped extensions.
raise
return None
|
def getdoc(obj):
"""Stable wrapper around inspect.getdoc.
This can't crash because of attribute problems.
It also attempts to call a getdoc() method on the given object. This
allows objects which provide their docstrings via non-standard mechanisms
(like Pyro proxies) to still be inspected by ipython's ? system."""
# Allow objects to offer customized documentation via a getdoc method:
try:
ds = obj.getdoc()
except Exception:
pass
else:
# if we get extra info, we add it to the normal docstring.
if isinstance(ds, basestring):
return inspect.cleandoc(ds)
try:
return inspect.getdoc(obj)
except Exception:
# Harden against an inspect failure, which can occur with
# SWIG-wrapped extensions.
return None
|
https://github.com/ipython/ipython/issues/1688
|
In [1]: %run err.py
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
C:\python\ipydevel\VENV\Py27\lib\site-packages\ipython-0.13.dev-py2.7.egg\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
166 else:
167 filename = fname
--> 168 exec compile(scripttext, filename, 'exec') in glob, loc
169 else:
170 def execfile(fname, *where):
C:\python\ipydevel\err.py in <module>()
5 b=2+4
6
----> 7 a()
C:\python\ipydevel\err.py in a()
2 def a():
3 a=1+2
----> 4 1/0
5 b=2+4
6
ZeroDivisionError: integer division or modulo by zero
|
ZeroDivisionError
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.