Skip to content

Commit

Permalink
Merge pull request #135 from pytest-dev/deprecate-py-std
Browse files Browse the repository at this point in the history
deprecate py.std and remove all uses from the own codebase/unrelated …
  • Loading branch information
RonnyPfannschmidt committed Jun 29, 2017
2 parents bb7fa9d + 7f46178 commit c34adde
Show file tree
Hide file tree
Showing 26 changed files with 159 additions and 92 deletions.
3 changes: 2 additions & 1 deletion py/_code/_assertionold.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import sys, inspect
from compiler import parse, ast, pycodegen
from py._code.assertion import BuiltinAssertionError, _format_explanation
import types

passthroughex = py.builtin._sysex

Expand Down Expand Up @@ -470,7 +471,7 @@ def check(s, frame=None):
def interpret(source, frame, should_fail=False):
module = Interpretable(parse(source, 'exec').node)
#print "got module", module
if isinstance(frame, py.std.types.FrameType):
if isinstance(frame, types.FrameType):
frame = py.code.Frame(frame)
try:
module.run(frame)
Expand Down
33 changes: 21 additions & 12 deletions py/_code/code.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import py
import sys
from inspect import CO_VARARGS, CO_VARKEYWORDS
from inspect import CO_VARARGS, CO_VARKEYWORDS, isclass

builtin_repr = repr

Expand All @@ -11,6 +11,9 @@
else:
from py._code._py2traceback import format_exception_only

import traceback


class Code(object):
""" wrapper around Python code objects """
def __init__(self, rawcode):
Expand All @@ -21,7 +24,7 @@ def __init__(self, rawcode):
self.firstlineno = rawcode.co_firstlineno - 1
self.name = rawcode.co_name
except AttributeError:
raise TypeError("not a code object: %r" %(rawcode,))
raise TypeError("not a code object: %r" % (rawcode,))
self.raw = rawcode

def __eq__(self, other):
Expand Down Expand Up @@ -106,7 +109,7 @@ def exec_(self, code, **vars):
"""
f_locals = self.f_locals.copy()
f_locals.update(vars)
py.builtin.exec_(code, self.f_globals, f_locals )
py.builtin.exec_(code, self.f_globals, f_locals)

def repr(self, object):
""" return a 'safe' (non-recursive, one-line) string repr for 'object'
Expand All @@ -130,6 +133,7 @@ def getargs(self, var=False):
pass # this can occur when using Psyco
return retval


class TracebackEntry(object):
""" a single entry in a traceback """

Expand All @@ -153,7 +157,7 @@ def relline(self):
return self.lineno - self.frame.code.firstlineno

def __repr__(self):
return "<TracebackEntry %s:%d>" %(self.frame.code.path, self.lineno+1)
return "<TracebackEntry %s:%d>" % (self.frame.code.path, self.lineno+1)

@property
def statement(self):
Expand Down Expand Up @@ -237,17 +241,19 @@ def __str__(self):
raise
except:
line = "???"
return " File %r:%d in %s\n %s\n" %(fn, self.lineno+1, name, line)
return " File %r:%d in %s\n %s\n" % (fn, self.lineno+1, name, line)

def name(self):
return self.frame.code.raw.co_name
name = property(name, None, None, "co_name of underlaying code")


class Traceback(list):
""" Traceback objects encapsulate and offer higher level
access to Traceback entries.
"""
Entry = TracebackEntry

def __init__(self, tb):
""" initialize from given python traceback object. """
if hasattr(tb, 'tb_next'):
Expand Down Expand Up @@ -362,7 +368,8 @@ def __init__(self, tup=None, exprinfo=None):
self.traceback = py.code.Traceback(self.tb)

def __repr__(self):
return "<ExceptionInfo %s tblen=%d>" % (self.typename, len(self.traceback))
return "<ExceptionInfo %s tblen=%d>" % (
self.typename, len(self.traceback))

def exconly(self, tryshort=False):
""" return the exception as a string
Expand Down Expand Up @@ -391,7 +398,7 @@ def _getreprcrash(self):
return ReprFileLocation(path, lineno+1, exconly)

def getrepr(self, showlocals=False, style="long",
abspath=False, tbfilter=True, funcargs=False):
abspath=False, tbfilter=True, funcargs=False):
""" return str()able representation of this exception info.
showlocals: show locals per traceback entry
style: long|short|no|native traceback style
Expand All @@ -401,13 +408,14 @@ def getrepr(self, showlocals=False, style="long",
"""
if style == 'native':
return ReprExceptionInfo(ReprTracebackNative(
py.std.traceback.format_exception(
traceback.format_exception(
self.type,
self.value,
self.traceback[0]._rawentry,
)), self._getreprcrash())

fmt = FormattedExcinfo(showlocals=showlocals, style=style,
fmt = FormattedExcinfo(
showlocals=showlocals, style=style,
abspath=abspath, tbfilter=tbfilter, funcargs=funcargs)
return fmt.repr_excinfo(self)

Expand All @@ -428,7 +436,8 @@ class FormattedExcinfo(object):
flow_marker = ">"
fail_marker = "E"

def __init__(self, showlocals=False, style="long", abspath=True, tbfilter=True, funcargs=False):
def __init__(self, showlocals=False, style="long",
abspath=True, tbfilter=True, funcargs=False):
self.showlocals = showlocals
self.style = style
self.tbfilter = tbfilter
Expand Down Expand Up @@ -521,7 +530,7 @@ def repr_locals(self, locals):
#else:
# self._line("%-10s =\\" % (name,))
# # XXX
# py.std.pprint.pprint(value, stream=self.excinfowriter)
# pprint.pprint(value, stream=self.excinfowriter)
return ReprLocals(lines)

def repr_traceback_entry(self, entry, excinfo=None):
Expand Down Expand Up @@ -779,7 +788,7 @@ def getrawcode(obj, trycall=True):
obj = getattr(obj, 'f_code', obj)
obj = getattr(obj, '__code__', obj)
if trycall and not hasattr(obj, 'co_firstlineno'):
if hasattr(obj, '__call__') and not py.std.inspect.isclass(obj):
if hasattr(obj, '__call__') and not isclass(obj):
x = getrawcode(obj.__call__, trycall=False)
if hasattr(x, 'co_firstlineno'):
return x
Expand Down
9 changes: 5 additions & 4 deletions py/_code/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,8 @@ def compile(self, filename=None, mode='exec',
if flag & _AST_FLAG:
return co
lines = [(x + "\n") for x in self.lines]
py.std.linecache.cache[filename] = (1, None, lines, filename)
import linecache
linecache.cache[filename] = (1, None, lines, filename)
return co

#
Expand Down Expand Up @@ -224,8 +225,8 @@ def getfslineno(obj):
code = py.code.Code(obj)
except TypeError:
try:
fn = (py.std.inspect.getsourcefile(obj) or
py.std.inspect.getfile(obj))
fn = (inspect.getsourcefile(obj) or
inspect.getfile(obj))
except TypeError:
return "", -1

Expand All @@ -248,7 +249,7 @@ def getfslineno(obj):

def findsource(obj):
try:
sourcelines, lineno = py.std.inspect.findsource(obj)
sourcelines, lineno = inspect.findsource(obj)
except py.builtin._sysex:
raise
except:
Expand Down
2 changes: 1 addition & 1 deletion py/_io/terminalwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def __init__(self, file=None, stringio=False, encoding=None):
if stringio:
self.stringio = file = py.io.TextIO()
else:
file = py.std.sys.stdout
from sys import stdout as file
elif py.builtin.callable(file) and not (
hasattr(file, "write") and hasattr(file, "flush")):
file = WriteFile(file, encoding=encoding)
Expand Down
24 changes: 19 additions & 5 deletions py/_log/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
debug=py.log.STDOUT,
command=None)
"""
import py, sys
import py
import sys
import syslog


class Message(object):
def __init__(self, keywords, args):
Expand Down Expand Up @@ -70,6 +73,7 @@ def __init__(self):

def getstate(self):
return self.keywords2consumer.copy()

def setstate(self, state):
self.keywords2consumer.clear()
self.keywords2consumer.update(state)
Expand Down Expand Up @@ -104,29 +108,35 @@ def setconsumer(self, keywords, consumer):
consumer = File(consumer)
self.keywords2consumer[keywords] = consumer


def default_consumer(msg):
""" the default consumer, prints the message to stdout (using 'print') """
sys.stderr.write(str(msg)+"\n")

default_keywordmapper = KeywordMapper()


def setconsumer(keywords, consumer):
default_keywordmapper.setconsumer(keywords, consumer)


def setstate(state):
default_keywordmapper.setstate(state)


def getstate():
return default_keywordmapper.getstate()

#
# Consumers
#


class File(object):
""" log consumer wrapping a file(-like) object """
def __init__(self, f):
assert hasattr(f, 'write')
#assert isinstance(f, file) or not hasattr(f, 'open')
# assert isinstance(f, file) or not hasattr(f, 'open')
self._file = f

def __call__(self, msg):
Expand All @@ -135,6 +145,7 @@ def __call__(self, msg):
if hasattr(self._file, 'flush'):
self._file.flush()


class Path(object):
""" log consumer that opens and writes to a Path """
def __init__(self, filename, append=False,
Expand All @@ -158,29 +169,32 @@ def __call__(self, msg):
if not self._buffering:
self._file.flush()


def STDOUT(msg):
""" consumer that writes to sys.stdout """
sys.stdout.write(str(msg)+"\n")


def STDERR(msg):
""" consumer that writes to sys.stderr """
sys.stderr.write(str(msg)+"\n")


class Syslog:
""" consumer that writes to the syslog daemon """

def __init__(self, priority = None):
def __init__(self, priority=None):
if priority is None:
priority = self.LOG_INFO
self.priority = priority

def __call__(self, msg):
""" write a message to the log """
py.std.syslog.syslog(self.priority, str(msg))
syslog.syslog(self.priority, str(msg))

for _prio in "EMERG ALERT CRIT ERR WARNING NOTICE INFO DEBUG".split():
_prio = "LOG_" + _prio
try:
setattr(Syslog, _prio, getattr(py.std.syslog, _prio))
setattr(Syslog, _prio, getattr(syslog, _prio))
except AttributeError:
pass
9 changes: 6 additions & 3 deletions py/_log/warning.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@ def _apiwarn(startversion, msg, stacklevel=2, function=None):
msg = "%s (since version %s)" %(msg, startversion)
warn(msg, stacklevel=stacklevel+1, function=function)


def warn(msg, stacklevel=1, function=None):
if function is not None:
filename = py.std.inspect.getfile(function)
import inspect
filename = inspect.getfile(function)
lineno = py.code.getrawcode(function).co_firstlineno
else:
try:
Expand Down Expand Up @@ -67,10 +69,11 @@ def warn(msg, stacklevel=1, function=None):
filename = module
path = py.path.local(filename)
warning = DeprecationWarning(msg, path, lineno)
py.std.warnings.warn_explicit(warning, category=Warning,
import warnings
warnings.warn_explicit(warning, category=Warning,
filename=str(warning.path),
lineno=warning.lineno,
registry=py.std.warnings.__dict__.setdefault(
registry=warnings.__dict__.setdefault(
"__warningsregistry__", {})
)

8 changes: 5 additions & 3 deletions py/_path/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,14 +189,16 @@ def load(self):
""" (deprecated) return object unpickled from self.read() """
f = self.open('rb')
try:
return py.error.checked_call(py.std.pickle.load, f)
import pickle
return py.error.checked_call(pickle.load, f)
finally:
f.close()

def move(self, target):
""" move this path to target. """
if target.relto(self):
raise py.error.EINVAL(target,
raise py.error.EINVAL(
target,
"cannot move path into a subdirectory of itself")
try:
self.rename(target)
Expand Down Expand Up @@ -226,7 +228,7 @@ def check(self, **kw):
path.check(file=1, link=1) # a link pointing to a file
"""
if not kw:
kw = {'exists' : 1}
kw = {'exists': 1}
return self.Checkers(self)._evaluate(kw)

def fnmatch(self, pattern):
Expand Down

0 comments on commit c34adde

Please sign in to comment.