Remove all usage of python2_3.py (#1939)

* Remove all usage of python2_3.py

Technically these functions were exported at the top level of the library, this removes them without warning... If we want to we can bring them back for there, but I honestly don't think its needed, as we are py3 only now and have been for multiple releases.

This may introduce a number of 'useless cast' or similar but those were always happening anyway

This PR brought to you by sed

* Update varname in hdf example to avoid collision with builtin

* Clean up some leftover comments surrounding imports of compat code

* Unnecessary string casts

* Additional unnecessary casts

* syntax error fix

* more unnecessary casts

* Yet more unnecessary casts
This commit is contained in:
Kyle Sunden 2021-08-01 23:43:32 -05:00 committed by GitHub
parent 1ddbfc8321
commit a472f8c5de
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
42 changed files with 133 additions and 205 deletions

View File

@ -32,7 +32,7 @@ p1.setAutoVisible(y=True)
#create numpy arrays
#make the numbers large to show that the xrange shows data from 10000 to all the way 0
#make the numbers large to show that the range shows data from 10000 to all the way 0
data1 = 10000 + 15000 * pg.gaussianFilter(np.random.random(size=10000), 10) + 3000 * np.random.random(size=10000)
data2 = 15000 + 15000 * pg.gaussianFilter(np.random.random(size=10000), 10) + 3000 * np.random.random(size=10000)

View File

@ -51,9 +51,9 @@ class HDF5Plot(pg.PlotCurveItem):
return # no ViewBox yet
# Determine what data range must be read from HDF5
xrange = vb.viewRange()[0]
start = max(0,int(xrange[0])-1)
stop = min(len(self.hdf5), int(xrange[1]+2))
range_ = vb.viewRange()[0]
start = max(0,int(range_[0])-1)
stop = min(len(self.hdf5), int(range_[1]+2))
# Decide by how much we should downsample
ds = int((stop-start) / self.limit) + 1

View File

@ -5,7 +5,6 @@ import time
import numpy as np
import pyqtgraph.multiprocess as mp
import pyqtgraph as pg
from pyqtgraph.python2_3 import xrange
print( "\n=================\nParallelize")
@ -32,7 +31,7 @@ start = time.time()
with pg.ProgressDialog('processing serially..', maximum=len(tasks)) as dlg:
for i, x in enumerate(tasks):
tot = 0
for j in xrange(size):
for j in range(size):
tot += j * x
results[i] = tot
dlg += 1
@ -46,7 +45,7 @@ start = time.time()
with mp.Parallelize(enumerate(tasks), results=results2, workers=1, progressDialog='processing serially (using Parallelizer)..') as tasker:
for i, x in tasker:
tot = 0
for j in xrange(size):
for j in range(size):
tot += j * x
tasker.results[i] = tot
print( "\nParallel time, 1 worker: %0.2f" % (time.time() - start))
@ -57,9 +56,8 @@ start = time.time()
with mp.Parallelize(enumerate(tasks), results=results3, progressDialog='processing in parallel..') as tasker:
for i, x in tasker:
tot = 0
for j in xrange(size):
for j in range(size):
tot += j * x
tasker.results[i] = tot
print( "\nParallel time, %d workers: %0.2f" % (mp.Parallelize.suggestedWorkerCount(), time.time() - start))
print( "Results match serial: %s" % str(results3 == results))

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
import numpy as np
import collections
import sys, os
@ -6,7 +7,6 @@ from pyqtgraph.Qt import QtGui, QtCore
from pyqtgraph.parametertree import Parameter, ParameterTree
from pyqtgraph.parametertree import types as pTypes
import pyqtgraph.configfile
from pyqtgraph.python2_3 import xrange
from time import perf_counter
@ -520,7 +520,7 @@ class Simulation:
dt = self.dt
tVals = np.linspace(0, dt*(nPts-1), nPts)
for cl in self.clocks.values():
for i in xrange(1,nPts):
for i in range(1,nPts):
nextT = tVals[i]
while True:
tau1, tau2 = cl.accelLimits()
@ -566,7 +566,7 @@ class Simulation:
## These are the set of proper times (in the reference frame) that will be simulated
ptVals = np.linspace(ref.pt, ref.pt + dt*(nPts-1), nPts)
for i in xrange(1,nPts):
for i in range(1,nPts):
## step reference clock ahead one time step in its proper time
nextPt = ptVals[i] ## this is where (when) we want to end up

View File

@ -12,7 +12,6 @@ This module exists to smooth out some of the differences between PySide and PyQt
import os, sys, re, time, subprocess, warnings
from ..python2_3 import asUnicode
PYSIDE = 'PySide'
PYSIDE2 = 'PySide2'
@ -73,7 +72,7 @@ class _StringIO(object):
self.data.append(data)
def getvalue(self):
return ''.join(map(asUnicode, self.data)).encode('utf8')
return ''.join(map(str, self.data)).encode('utf8')
def _loadUiType(uiFile):

View File

@ -10,7 +10,6 @@ of a large group of widgets.
from .Qt import QtCore, QtGui
import weakref, inspect
from .python2_3 import asUnicode
__all__ = ['WidgetGroup']
@ -45,7 +44,7 @@ def comboState(w):
except AttributeError:
pass
if data is None:
return asUnicode(w.itemText(ind))
return str(w.itemText(ind))
else:
return data

View File

@ -9,7 +9,7 @@ __version__ = '0.12.2'
### import all the goodies and add some helper functions for easy CLI use
## 'Qt' is a local module; it is intended mainly to cover up the differences
## between PyQt4 and PySide.
## between PyQt and PySide.
from .Qt import QtCore, QtGui, mkQApp
from .Qt import exec_ as exec
@ -22,14 +22,6 @@ import numpy ## pyqtgraph requires numpy
import os, sys
## check python version
## Allow anything >= 2.7
if sys.version_info[0] < 2 or (sys.version_info[0] == 2 and sys.version_info[1] < 6):
raise Exception("Pyqtgraph requires Python version 2.6 or greater (this is %d.%d)" % (sys.version_info[0], sys.version_info[1]))
## helpers for 2/3 compatibility
from . import python2_3
## in general openGL is poorly supported with Qt+GraphicsView.
## we only enable it where the performance benefit is critical.
## Note this only applies to 2D graphics; 3D graphics always use OpenGL.
@ -282,7 +274,6 @@ from .ThreadsafeTimer import *
# indirect imports used within library
from .GraphicsScene import GraphicsScene
from .python2_3 import asUnicode
from .util.cupy_helper import getCupy
# indirect imports known to be used outside of the library

View File

@ -14,7 +14,6 @@ import numpy
from collections import OrderedDict
import tempfile
from . import units
from .python2_3 import asUnicode, basestring
from .Qt import QtCore
from .Point import Point
from .colormap import ColorMap
@ -40,7 +39,7 @@ class ParseError(Exception):
def writeConfigFile(data, fname):
s = genString(data)
with open(fname, 'w') as fd:
with open(fname, 'wt') as fd:
fd.write(s)
@ -56,8 +55,8 @@ def readConfigFile(fname):
try:
#os.chdir(newDir) ## bad.
with open(fname) as fd:
s = asUnicode(fd.read())
with open(fname, "rt") as fd:
s = fd.read()
s = s.replace("\r\n", "\n")
s = s.replace("\r", "\n")
data = parseString(s)[1]
@ -73,7 +72,7 @@ def readConfigFile(fname):
def appendConfigFile(data, fname):
s = genString(data)
with open(fname, 'a') as fd:
with open(fname, 'at') as fd:
fd.write(s)
@ -97,7 +96,7 @@ def genString(data, indent=''):
def parseString(lines, start=0):
data = OrderedDict()
if isinstance(lines, basestring):
if isinstance(lines, str):
lines = lines.replace("\\\n", "")
lines = lines.split('\n')
lines = [l for l in lines if re.search(r'\S', l) and not re.match(r'\s*#', l)] ## remove empty lines

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from ..Qt import QtCore, QtGui
from ..python2_3 import asUnicode
class CmdInput(QtGui.QLineEdit):
@ -25,10 +25,10 @@ class CmdInput(QtGui.QLineEdit):
self.execCmd()
else:
super().keyPressEvent(ev)
self.history[0] = asUnicode(self.text())
self.history[0] = self.text()
def execCmd(self):
cmd = asUnicode(self.text())
cmd = self.text()
if len(self.history) == 1 or cmd != self.history[1]:
self.history.insert(1, cmd)
self.history[0] = ""

View File

@ -3,7 +3,6 @@ import sys, re, traceback, subprocess
import pickle
from ..Qt import QtCore, QtGui, QT_LIB
from ..python2_3 import basestring
from .. import exceptionHandling as exceptionHandling
from .. import getConfigOption
from ..functions import SignalBlock
@ -454,7 +453,7 @@ class ConsoleWidget(QtGui.QWidget):
if filterStr != '':
if isinstance(exc, Exception):
msg = traceback.format_exception_only(type(exc), exc)
elif isinstance(exc, basestring):
elif isinstance(exc, str):
msg = exc
else:
msg = repr(exc)

View File

@ -3,7 +3,6 @@ from ..Qt import QtCore, QtGui
from .DockDrop import *
from ..widgets.VerticalLabel import VerticalLabel
from ..python2_3 import asUnicode
class Dock(QtGui.QWidget, DockDrop):
@ -125,7 +124,7 @@ class Dock(QtGui.QWidget, DockDrop):
"""
Gets the text displayed in the title bar for this dock.
"""
return asUnicode(self.label.text())
return self.label.text()
def setTitle(self, text):
"""

View File

@ -4,7 +4,6 @@ from ..Qt import QtGui
from .Container import *
from .DockDrop import *
from .Dock import Dock
from ..python2_3 import basestring
class DockArea(Container, QtGui.QWidget, DockDrop):
@ -61,7 +60,7 @@ class DockArea(Container, QtGui.QWidget, DockDrop):
container = self.topContainer
neighbor = None
else:
if isinstance(relativeTo, basestring):
if isinstance(relativeTo, str):
relativeTo = self.docks[relativeTo]
container = self.getContainer(relativeTo)
if container is None:

View File

@ -3,7 +3,6 @@ from ..Qt import QtCore
from .Exporter import Exporter
from ..parametertree import Parameter
from .. import PlotItem
from ..python2_3 import asUnicode
translate = QtCore.QCoreApplication.translate
@ -60,7 +59,7 @@ class CSVExporter(Exporter):
sep = '\t'
with open(fileName, 'w') as fd:
fd.write(sep.join(map(asUnicode, header)) + '\n')
fd.write(sep.join(map(str, header)) + '\n')
i = 0
numFormat = '%%0.%dg' % self.params['precision']
numRows = max([len(d[0]) for d in data])

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
from ..widgets.FileDialog import FileDialog
from ..Qt import QtGui, QtCore
from ..python2_3 import asUnicode, basestring
from ..GraphicsScene import GraphicsScene
import os, re
LastExportDirectory = None
@ -49,7 +48,7 @@ class Exporter(object):
self.fileDialog.setFileMode(QtGui.QFileDialog.FileMode.AnyFile)
self.fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptMode.AcceptSave)
if filter is not None:
if isinstance(filter, basestring):
if isinstance(filter, str):
self.fileDialog.setNameFilter(filter)
elif isinstance(filter, list):
self.fileDialog.setNameFilters(filter)
@ -63,13 +62,12 @@ class Exporter(object):
return
def fileSaveFinished(self, fileName):
fileName = asUnicode(fileName)
global LastExportDirectory
LastExportDirectory = os.path.split(fileName)[0]
## If file name does not match selected extension, append it now
ext = os.path.splitext(fileName)[1].lower().lstrip('.')
selectedExt = re.search(r'\*\.(\w+)\b', asUnicode(self.fileDialog.selectedNameFilter()))
selectedExt = re.search(r'\*\.(\w+)\b', self.fileDialog.selectedNameFilter())
if selectedExt is not None:
selectedExt = selectedExt.groups()[0].lower()
if ext != selectedExt:

View File

@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
from .Exporter import Exporter
from ..python2_3 import asUnicode
from ..parametertree import Parameter
from ..Qt import QtGui, QtCore, QtSvg
from .. import debug
@ -79,7 +78,7 @@ class SVGExporter(Exporter):
QtGui.QApplication.clipboard().setMimeData(md)
else:
with open(fileName, 'wb') as fh:
fh.write(asUnicode(xml).encode('utf-8'))
fh.write(str(xml).encode('utf-8'))
# Includes space for extra attributes
xmlHeader = """\

View File

@ -17,7 +17,6 @@ from .. import configfile as configfile
from .. import dockarea as dockarea
from . import FlowchartGraphicsView
from .. import functions as fn
from ..python2_3 import asUnicode
def strDict(d):
return dict([(str(k), v) for k, v in d.items()])
@ -512,7 +511,6 @@ class Flowchart(Node):
self.fileDialog.fileSelected.connect(self.loadFile)
return
## NOTE: was previously using a real widget for the file dialog's parent, but this caused weird mouse event bugs..
fileName = asUnicode(fileName)
state = configfile.readConfigFile(fileName)
self.restoreState(state, clear=True)
self.viewBox.autoRange()
@ -532,7 +530,6 @@ class Flowchart(Node):
self.fileDialog.show()
self.fileDialog.fileSelected.connect(self.saveFile)
return
fileName = asUnicode(fileName)
configfile.writeConfigFile(self.saveState(), fileName)
self.sigFileSaved.emit(fileName)
@ -653,7 +650,7 @@ class FlowchartCtrlWidget(QtGui.QWidget):
#self.setCurrentFile(newFile)
def fileSaved(self, fileName):
self.setCurrentFile(asUnicode(fileName))
self.setCurrentFile(fileName)
self.ui.saveBtn.success("Saved.")
def saveClicked(self):
@ -682,7 +679,7 @@ class FlowchartCtrlWidget(QtGui.QWidget):
#self.setCurrentFile(newFile)
def setCurrentFile(self, fileName):
self.currentFileName = asUnicode(fileName)
self.currentFileName = fileName
if fileName is None:
self.ui.fileNameLabel.setText("<b>[ new ]</b>")
else:

View File

@ -3,7 +3,6 @@ import numpy as np
from . import functions
from ... import functions as pgfn
from .common import *
from ...python2_3 import xrange
from ... import PolyLineROI
from ... import Point
from ... import metaarray as metaarray
@ -320,7 +319,7 @@ class RemovePeriodic(CtrlNode):
## flatten spikes at f0 and harmonics
f0 = self.ctrls['f0'].value()
for i in xrange(1, self.ctrls['harmonics'].value()+2):
for i in range(1, self.ctrls['harmonics'].value()+2):
f = f0 * i # target frequency
## determine index range to check for this frequency

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
import numpy as np
from ...metaarray import MetaArray
from ...python2_3 import xrange
def downsample(data, n, axis=0, xvals='subsample'):
@ -308,7 +307,7 @@ def suggestDType(x):
return float
elif isinstance(x, int):
return int
#elif isinstance(x, basestring): ## don't try to guess correct string length; use object instead.
#elif isinstance(x, str): ## don't try to guess correct string length; use object instead.
#return '<U%d' % len(x)
else:
return object
@ -331,7 +330,7 @@ def removePeriodic(data, f0=60.0, dt=None, harmonics=10, samples=4):
freqs = np.linspace(0.0, (len(ft)-1) * df, len(ft))
## flatten spikes at f0 and harmonics
for i in xrange(1, harmonics + 2):
for i in range(1, harmonics + 2):
f = f0 * i # target frequency
## determine index range to check for this frequency

View File

@ -23,7 +23,6 @@ from .Qt import QtGui, QtCore, QT_LIB, QtVersion
from . import Qt
from .metaarray import MetaArray
from collections import OrderedDict
from .python2_3 import asUnicode, basestring
# in order of appearance in this file.
# add new functions to this list only if they are to reside in pg namespace.
@ -64,7 +63,7 @@ Colors = {
's': QtGui.QColor(100,100,150,255),
}
SI_PREFIXES = asUnicode('yzafpnµm kMGTPEZY')
SI_PREFIXES = 'yzafpnµm kMGTPEZY'
SI_PREFIXES_ASCII = 'yzafpnum kMGTPEZY'
SI_PREFIX_EXPONENTS = dict([(SI_PREFIXES[i], (i-8)*3) for i in range(len(SI_PREFIXES))])
SI_PREFIX_EXPONENTS['u'] = -6
@ -131,7 +130,7 @@ def siFormat(x, precision=3, suffix='', space=True, error=None, minVal=1e-25, al
return fmt % (x*p, pref, suffix)
else:
if allowUnicode:
plusminus = space + asUnicode("±") + space
plusminus = space + "±" + space
else:
plusminus = " +/- "
fmt = "%." + str(precision) + "g%s%s%s%s"
@ -163,7 +162,6 @@ def siParse(s, regex=FLOAT_REGEX, suffix=None):
contains a suffix, it is discarded. This enables interpreting
characters following the numerical value as an SI prefix.
"""
s = asUnicode(s)
s = s.strip()
if suffix is not None and len(suffix) > 0:
if s[-len(suffix):] != suffix:
@ -253,7 +251,7 @@ def mkColor(*args):
"""
err = 'Not sure how to make a color from "%s"' % str(args)
if len(args) == 1:
if isinstance(args[0], basestring):
if isinstance(args[0], str):
c = args[0]
if len(c) == 1:
try:
@ -2197,9 +2195,9 @@ def arrayToQPolygonF(x, y):
#index = tetFields[0] + tetFields[1]*2 + tetFields[2]*4 + tetFields[3]*8
### add facets
#for i in xrange(index.shape[0]): # data x-axis
#for j in xrange(index.shape[1]): # data y-axis
#for k in xrange(index.shape[2]): # data z-axis
#for i in range(index.shape[0]): # data x-axis
#for j in range(index.shape[1]): # data y-axis
#for k in range(index.shape[2]): # data z-axis
#for f in indexFacets[index[i,j,k]]: # faces to generate for this tet
#pts = []
#for l in [0,1,2]: # points in this face

View File

@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore
from ..python2_3 import asUnicode
import numpy as np
from ..Point import Point
from .. import debug as debug
@ -314,16 +313,15 @@ class AxisItem(GraphicsWidget):
if not self.autoSIPrefix or self.autoSIPrefixScale == 1.0:
units = ''
else:
units = asUnicode('(x%g)') % (1.0/self.autoSIPrefixScale)
units = '(x%g)' % (1.0/self.autoSIPrefixScale)
else:
#print repr(self.labelUnitPrefix), repr(self.labelUnits)
units = asUnicode('(%s%s)') % (asUnicode(self.labelUnitPrefix), asUnicode(self.labelUnits))
units = '(%s%s)' % (self.labelUnitPrefix, self.labelUnits)
s = asUnicode('%s %s') % (asUnicode(self.labelText), asUnicode(units))
s = '%s %s' % (self.labelText, units)
style = ';'.join(['%s: %s' % (k, self.labelStyle[k]) for k in self.labelStyle])
return asUnicode("<span style='%s'>%s</span>") % (style, asUnicode(s))
return "<span style='%s'>%s</span>" % (style, s)
def _updateMaxTextSize(self, x):
## Informs that the maximum tick size orthogonal to the axis has
@ -1070,7 +1068,7 @@ class AxisItem(GraphicsWidget):
if s is None:
rects.append(None)
else:
br = p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignmentFlag.AlignCenter, asUnicode(s))
br = p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignmentFlag.AlignCenter, s)
## boundingRect is usually just a bit too large
## (but this probably depends on per-font metrics?)
br.setHeight(br.height() * 0.8)
@ -1112,7 +1110,6 @@ class AxisItem(GraphicsWidget):
vstr = strings[j]
if vstr is None: ## this tick was ignored because it is out of bounds
continue
vstr = asUnicode(vstr)
x = tickPositions[i][j]
#textRect = p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignmentFlag.AlignCenter, vstr)
textRect = rects[j]

View File

@ -1041,7 +1041,7 @@ def isSequence(obj):
##print rec1, dtype
#arr = np.empty(len(self), dtype=dtype)
#arr[0] = tuple(rec1.values())
#for i in xrange(1, len(self)):
#for i in range(1, len(self)):
#arr[i] = tuple(self[i].values())
#return arr
@ -1052,7 +1052,7 @@ def isSequence(obj):
#return self.data[arg]
#def __getitem__list(self, arg):
#if isinstance(arg, basestring):
#if isinstance(arg, str):
#return [d.get(arg, None) for d in self.data]
#elif isinstance(arg, int):
#return self.data[arg]
@ -1063,7 +1063,7 @@ def isSequence(obj):
#raise TypeError(type(arg))
#def __getitem__dict(self, arg):
#if isinstance(arg, basestring):
#if isinstance(arg, str):
#return self.data[arg]
#elif isinstance(arg, int):
#return dict([(k, v[arg]) for k, v in self.data.items()])
@ -1080,7 +1080,7 @@ def isSequence(obj):
#self.data[arg] = val
#def __setitem__list(self, arg, val):
#if isinstance(arg, basestring):
#if isinstance(arg, str):
#if len(val) != len(self.data):
#raise Exception("Values (%d) and data set (%d) are not the same length." % (len(val), len(self.data)))
#for i, rec in enumerate(self.data):
@ -1094,7 +1094,7 @@ def isSequence(obj):
#raise TypeError(type(arg))
#def __setitem__dict(self, arg, val):
#if isinstance(arg, basestring):
#if isinstance(arg, str):
#if len(val) != len(self.data[arg]):
#raise Exception("Values (%d) and data set (%d) are not the same length." % (len(val), len(self.data[arg])))
#self.data[arg] = val
@ -1109,13 +1109,13 @@ def isSequence(obj):
#def _orderArgs(self, args):
### return args in (int, str) order
#if isinstance(args[0], basestring):
#if isinstance(args[0], str):
#return (args[1], args[0])
#else:
#return args
#def __iter__(self):
#for i in xrange(len(self)):
#for i in range(len(self)):
#yield self[i]
#def __len__(self):

View File

@ -21,7 +21,6 @@ from ... import functions as fn
from ... import icons
from ...Qt import QtGui, QtCore, QT_LIB
from ...WidgetGroup import WidgetGroup
from ...python2_3 import basestring
from ...widgets.FileDialog import FileDialog
translate = QtCore.QCoreApplication.translate
@ -252,7 +251,7 @@ class PlotItem(GraphicsWidget):
labels[label] = kargs[label]
del kargs[label]
for k in labels:
if isinstance(labels[k], basestring):
if isinstance(labels[k], str):
labels[k] = (labels[k],)
self.setLabel(k, *labels[k])
@ -1133,7 +1132,7 @@ class PlotItem(GraphicsWidget):
if k == 'title':
self.setTitle(v)
else:
if isinstance(v, basestring):
if isinstance(v, str):
v = (v,)
self.setLabel(k, *v)

View File

@ -5,7 +5,6 @@ import math
from copy import deepcopy
import numpy as np
from ...Qt import QtGui, QtCore
from ...python2_3 import basestring
from ...Point import Point
from ... import functions as fn
from .. ItemGroup import ItemGroup
@ -306,7 +305,7 @@ class ViewBox(GraphicsWidget):
for v in state['linkedViews']:
if isinstance(v, weakref.ref):
v = v()
if v is None or isinstance(v, basestring):
if v is None or isinstance(v, str):
views.append(v)
else:
views.append(v.name)
@ -936,7 +935,7 @@ class ViewBox(GraphicsWidget):
Link X or Y axes of two views and unlink any previously connected axes. *axis* must be ViewBox.XAxis or ViewBox.YAxis.
If view is None, the axis is left unlinked.
"""
if isinstance(view, basestring):
if isinstance(view, str):
if view == '':
view = None
else:
@ -964,7 +963,7 @@ class ViewBox(GraphicsWidget):
pass
if view is None or isinstance(view, basestring):
if view is None or isinstance(view, str):
self.state['linkedViews'][axis] = view
else:
self.state['linkedViews'][axis] = weakref.ref(view)
@ -997,7 +996,7 @@ class ViewBox(GraphicsWidget):
## Return the linked view for axis *ax*.
## this method _always_ returns either a ViewBox or None.
v = self.state['linkedViews'][ax]
if v is None or isinstance(v, basestring):
if v is None or isinstance(v, str):
return None
else:
return v() ## dereference weakref pointer. If the reference is dead, this returns None
@ -1642,7 +1641,7 @@ class ViewBox(GraphicsWidget):
for ax in [0,1]:
link = self.state['linkedViews'][ax]
if isinstance(link, basestring): ## axis has not been linked yet; see if it's possible now
if isinstance(link, str): ## axis has not been linked yet; see if it's possible now
for v in nv:
if link == v.name:
self.linkView(ax, v)

View File

@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
from ...Qt import QtCore, QtGui, QT_LIB
from ...python2_3 import asUnicode
from ...WidgetGroup import WidgetGroup
import importlib
@ -238,7 +237,7 @@ class ViewBoxMenu(QtGui.QMenu):
for i in [0,1]:
c = self.ctrl[i].linkCombo
current = asUnicode(c.currentText())
current = c.currentText()
c.blockSignals(True)
changed = True
try:

View File

@ -13,7 +13,6 @@ More info at http://www.scipy.org/Cookbook/MetaArray
import copy, os
import pickle
import numpy as np
from ..python2_3 import basestring
import warnings
@ -121,7 +120,7 @@ class MetaArray(object):
defaultCompression = None
## Types allowed as axis or column names
nameTypes = [basestring, tuple]
nameTypes = [str, tuple]
@staticmethod
def isNameType(var):
return any(isinstance(var, t) for t in MetaArray.nameTypes)
@ -412,7 +411,7 @@ class MetaArray(object):
if type(axis) == int:
ind = [slice(None)]*axis
ind.append(order)
elif isinstance(axis, basestring):
elif isinstance(axis, str):
ind = (slice(axis, order),)
return self[tuple(ind)]
@ -469,7 +468,7 @@ class MetaArray(object):
return tuple(nInd)
def _interpretAxis(self, axis):
if isinstance(axis, basestring) or isinstance(axis, tuple):
if isinstance(axis, (str, tuple)):
return self._getAxis(axis)
else:
return axis
@ -937,7 +936,7 @@ class MetaArray(object):
val = root.attrs[k]
if isinstance(val, bytes):
val = val.decode()
if isinstance(val, basestring): ## strings need to be re-evaluated to their original types
if isinstance(val, str): ## strings need to be re-evaluated to their original types
try:
val = eval(val)
except:

View File

@ -2,7 +2,6 @@
import os, sys, time, multiprocessing, re
from .processes import ForkedProcess
from .remoteproxy import ClosedError
from ..python2_3 import basestring, xrange
class CanceledError(Exception):
@ -64,7 +63,7 @@ class Parallelize(object):
self.showProgress = False
if progressDialog is not None:
self.showProgress = True
if isinstance(progressDialog, basestring):
if isinstance(progressDialog, str):
progressDialog = {'labelText': progressDialog}
from ..widgets.ProgressDialog import ProgressDialog
self.progressDlg = ProgressDialog(**progressDialog)
@ -120,7 +119,7 @@ class Parallelize(object):
## break up tasks into one set per worker
workers = self.workers
chunks = [[] for i in xrange(workers)]
chunks = [[] for i in range(workers)]
i = 0
for i in range(len(self.tasks)):
chunks[i%workers].append(self.tasks[i])

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
import numpy as np
from ..Qt import QtGui
from ..python2_3 import xrange
class MeshData(object):
@ -209,7 +208,7 @@ class MeshData(object):
faceNorms = self.faceNormals()
vertFaces = self.vertexFaces()
self._vertexNormals = np.empty(self._vertexes.shape, dtype=float)
for vindex in xrange(self._vertexes.shape[0]):
for vindex in range(self._vertexes.shape[0]):
faces = vertFaces[vindex]
if len(faces) == 0:
self._vertexNormals[vindex] = (0,0,0)
@ -318,7 +317,7 @@ class MeshData(object):
self._vertexFaces = []
self._faceNormals = None
self._vertexNormals = None
for i in xrange(faces.shape[0]):
for i in range(faces.shape[0]):
face = faces[i]
inds = []
for j in range(face.shape[0]):
@ -350,8 +349,8 @@ class MeshData(object):
Return list mapping each vertex index to a list of face indexes that use the vertex.
"""
if self._vertexFaces is None:
self._vertexFaces = [[] for i in xrange(len(self.vertexes()))]
for i in xrange(self._faces.shape[0]):
self._vertexFaces = [[] for i in range(len(self.vertexes()))]
for i in range(self._faces.shape[0]):
face = self._faces[i]
for ind in face:
self._vertexFaces[ind].append(i)

View File

@ -3,7 +3,6 @@ from .. import functions as fn
from ..Qt import QtCore
import weakref, re
from collections import OrderedDict
from ..python2_3 import asUnicode, basestring
from .ParameterItem import ParameterItem
import warnings
@ -190,7 +189,7 @@ class Parameter(QtCore.QObject):
self.blockTreeChangeEmit = 0
#self.monitoringChildren = False ## prevent calling monitorChildren more than once
if not isinstance(name, basestring):
if not isinstance(name, str):
raise Exception("Parameter must have a string name specified in opts.")
self.setName(name)
@ -701,7 +700,7 @@ class Parameter(QtCore.QObject):
param[('child', 'grandchild')] = value
"""
if isinstance(names, basestring):
if isinstance(names, str):
names = (names,)
return self.param(*names).setValue(value)
@ -730,7 +729,7 @@ class Parameter(QtCore.QObject):
return self.child(*names)
def __repr__(self):
return asUnicode("<%s '%s' at 0x%x>") % (self.__class__.__name__, self.name(), id(self))
return "<%s '%s' at 0x%x>" % (self.__class__.__name__, self.name(), id(self))
def __getattr__(self, attr):
## Leaving this undocumented because I might like to remove it in the future..

View File

@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore
from ..python2_3 import asUnicode
translate = QtCore.QCoreApplication.translate
@ -138,7 +137,7 @@ class ParameterItem(QtGui.QTreeWidgetItem):
if self.ignoreNameColumnChange:
return
try:
newName = self.param.setName(asUnicode(self.text(col)))
newName = self.param.setName(str(self.text(col)))
except Exception:
self.setText(0, self.param.name())
raise

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from ..Qt import QtCore, QtGui, QtWidgets, QT_LIB
from ..python2_3 import asUnicode
from .Parameter import Parameter, registerParameterType
from .ParameterItem import ParameterItem
from ..widgets.SpinBox import SpinBox
@ -146,8 +146,8 @@ class WidgetParameterItem(ParameterItem):
w = QtWidgets.QLineEdit()
w.setStyleSheet('border: 0px')
w.sigChanged = w.editingFinished
w.value = lambda: asUnicode(w.text())
w.setValue = lambda v: w.setText(asUnicode(v))
w.value = w.text
w.setValue = w.setText
w.sigChanging = w.textChanged
elif t == 'color':
w = ColorButton()
@ -168,7 +168,7 @@ class WidgetParameterItem(ParameterItem):
self.hideWidget = False
self.asSubItem = True
else:
raise Exception("Unknown type '%s'" % asUnicode(t))
raise Exception("Unknown type '%s'" % str(t))
return w
def widgetEventFilter(self, obj, ev):
@ -231,11 +231,11 @@ class WidgetParameterItem(ParameterItem):
value = self.param.value()
opts = self.param.opts
if isinstance(self.widget, QtWidgets.QAbstractSpinBox):
text = asUnicode(self.widget.lineEdit().text())
text = self.widget.lineEdit().text()
elif isinstance(self.widget, QtWidgets.QComboBox):
text = self.widget.currentText()
else:
text = asUnicode(value)
text = str(value)
self.displayLabel.setText(text)
def widgetValueChanged(self):
@ -388,7 +388,7 @@ class SimpleParameter(Parameter):
'int': int,
'float': float,
'bool': bool,
'str': asUnicode,
'str': str,
'color': self._interpColor,
'colormap': self._interpColormap,
}[self.opts['type']]
@ -480,7 +480,7 @@ class GroupParameterItem(ParameterItem):
"""
if self.addWidget.currentIndex() == 0:
return
typ = asUnicode(self.addWidget.currentText())
typ = self.addWidget.currentText()
self.param.addNew(typ)
self.addWidget.setCurrentIndex(0)
@ -579,7 +579,7 @@ class ListParameterItem(WidgetParameterItem):
return w
def value(self):
key = asUnicode(self.widget.currentText())
key = self.widget.currentText()
return self.forward.get(key, None)
@ -601,7 +601,7 @@ class ListParameterItem(WidgetParameterItem):
self.forward, self.reverse = ListParameter.mapping(limits)
try:
self.widget.blockSignals(True)
val = self.targetValue #asUnicode(self.widget.currentText())
val = self.targetValue
self.widget.clear()
for k in self.forward:
@ -663,7 +663,7 @@ class ListParameter(Parameter):
reverse[1].append(k)
else:
for v in limits:
n = asUnicode(v)
n = str(v)
forward[n] = v
reverse[0].append(v)
reverse[1].append(n)
@ -877,7 +877,7 @@ class FileParameterItem(WidgetParameterItem):
def setValue(self, value):
self._value = value
self.widget.setText(asUnicode(value))
self.widget.setText(str(value))
def value(self):
return self._value
@ -919,7 +919,7 @@ class FileParameterItem(WidgetParameterItem):
lbl = self.displayLabel
if value is None:
value = self.param.value()
value = asUnicode(value)
value = str(value)
font = lbl.font()
metrics = QtGui.QFontMetricsF(font)
value = metrics.elidedText(value, QtCore.Qt.TextElideMode.ElideLeft, lbl.width()-5)
@ -985,7 +985,7 @@ class SliderParameterItem(WidgetParameterItem):
def updateDisplayLabel(self, value=None):
if value is None:
value = self.param.value()
value = asUnicode(value)
value = str(value)
if self._suffix is None:
suffixTxt = ''
else:

View File

@ -1,25 +0,0 @@
# -*- coding: utf-8 -*-
"""
Helper functions that smooth out the differences between python 2 and 3.
"""
import sys
def asUnicode(x):
if sys.version_info[0] == 2:
if isinstance(x, unicode):
return x
elif isinstance(x, str):
return x.decode('UTF-8')
else:
return unicode(x)
else:
return str(x)
if sys.version_info[0] == 3:
basestring = str
xrange = range
else:
import __builtin__
basestring = __builtin__.basestring
xrange = __builtin__.xrange

View File

@ -8,7 +8,6 @@ import sys
from .colorama.winterm import WinTerm, WinColor, WinStyle
from .colorama.win32 import windll
from ..python2_3 import basestring
_WIN = sys.platform.startswith('win')
if windll is not None:
@ -63,7 +62,7 @@ def cprint(stream, *args, **kwds):
cprint('stderr', 1, 'This is in red.', -1)
"""
if isinstance(stream, basestring):
if isinstance(stream, str):
stream = kwds.get('stream', 'stdout')
err = stream == 'stderr'
stream = getattr(sys, stream)
@ -74,7 +73,7 @@ def cprint(stream, *args, **kwds):
if _WIN:
# convert to win32 calls
for arg in args:
if isinstance(arg, basestring):
if isinstance(arg, str):
stream.write(arg)
else:
kwds = WIN[arg]
@ -82,14 +81,14 @@ def cprint(stream, *args, **kwds):
else:
# convert to ANSI
for arg in args:
if isinstance(arg, basestring):
if isinstance(arg, str):
stream.write(arg)
else:
stream.write(ANSI[arg])
else:
# ignore colors
for arg in args:
if isinstance(arg, basestring):
if isinstance(arg, str):
stream.write(arg)
def cout(*args):

View File

@ -2,7 +2,6 @@
import sys
from ..Qt import QtGui
from collections import OrderedDict
from ..python2_3 import asUnicode, basestring
__all__ = ['ComboBox']
@ -64,7 +63,7 @@ class ComboBox(QtGui.QComboBox):
"""
if self.count() == 0:
return None
text = asUnicode(self.currentText())
text = self.currentText()
return self._items[text]
def ignoreIndexChange(func):
@ -131,7 +130,7 @@ class ComboBox(QtGui.QComboBox):
# current index has changed; need to remember new 'chosen text'
if self._ignoreIndexChange:
return
self._chosenText = asUnicode(self.currentText())
self._chosenText = self.currentText()
def setCurrentIndex(self, index):
QtGui.QComboBox.setCurrentIndex(self, index)
@ -160,7 +159,7 @@ class ComboBox(QtGui.QComboBox):
def addItem(self, *args, **kwds):
# Need to handle two different function signatures for QComboBox.addItem
try:
if isinstance(args[0], basestring):
if isinstance(args[0], str):
text = args[0]
if len(args) == 2:
value = args[1]
@ -230,7 +229,7 @@ class ComboBox(QtGui.QComboBox):
except AttributeError:
pass
if data is None:
return asUnicode(self.itemText(ind))
return self.itemText(ind)
else:
return data

View File

@ -4,7 +4,6 @@ from .. import parametertree as ptree
import numpy as np
from collections import OrderedDict
from .. import functions as fn
from ..python2_3 import basestring
__all__ = ['DataFilterWidget']
@ -196,7 +195,7 @@ class EnumFilterItem(ptree.types.SimpleParameter):
if isinstance(valopts, bool):
enabled = valopts
vname = str(val)
elif isinstance(valopts, basestring):
elif isinstance(valopts, str):
enabled = True
vname = valopts
elif isinstance(valopts, tuple):

View File

@ -2,7 +2,6 @@
from ..Qt import QtGui
from collections import OrderedDict
from .TableWidget import TableWidget
from ..python2_3 import asUnicode
import types, traceback
import numpy as np
@ -55,7 +54,7 @@ class DataTreeWidget(QtGui.QTreeWidget):
if len(desc) > 100:
desc = desc[:97] + '...'
if widget is None:
widget = QtGui.QPlainTextEdit(asUnicode(data))
widget = QtGui.QPlainTextEdit(str(data))
widget.setMaximumHeight(200)
widget.setReadOnly(True)
@ -69,7 +68,7 @@ class DataTreeWidget(QtGui.QTreeWidget):
# recurse to children
for key, data in childs.items():
self.buildTree(data, node, asUnicode(key), path=path+(key,))
self.buildTree(data, node, str(key), path=path+(key,))
def parse(self, data):
"""
@ -117,11 +116,11 @@ class DataTreeWidget(QtGui.QTreeWidget):
#(i, {'file': child[0], 'line': child[1], 'function': child[2], 'code': child[3]})
#for i, child in enumerate(frames)])
#childs = OrderedDict([(i, ch) for i,ch in enumerate(frames)])
widget = QtGui.QPlainTextEdit(asUnicode('\n'.join(frames)))
widget = QtGui.QPlainTextEdit('\n'.join(frames))
widget.setMaximumHeight(200)
widget.setReadOnly(True)
else:
desc = asUnicode(data)
desc = str(data)
return typeStr, desc, childs, widget

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore
from .PathButton import PathButton
from ..python2_3 import basestring
__all__ = ['GroupBox']
@ -41,7 +41,7 @@ class GroupBox(QtGui.QGroupBox):
self.collapseBtn.clicked.connect(self.toggleCollapsed)
if len(args) > 0 and isinstance(args[0], basestring):
if len(args) > 0 and isinstance(args[0], str):
self.setTitle(args[0])
def toggleCollapsed(self):

View File

@ -4,7 +4,6 @@ import decimal
import re
from ..Qt import QtGui, QtCore
from ..python2_3 import asUnicode, basestring
from ..SignalProxy import SignalProxy
from .. import functions as fn
@ -90,7 +89,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
'decimals': 6,
'format': asUnicode("{scaledValue:.{decimals}g}{suffixGap}{siPrefix}{suffix}"),
'format': "{scaledValue:.{decimals}g}{suffixGap}{siPrefix}{suffix}",
'regex': fn.FLOAT_REGEX,
'evalFunc': decimal.Decimal,
@ -99,7 +98,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
self.decOpts = ['step', 'minStep']
self.val = decimal.Decimal(asUnicode(value)) ## Value is precise decimal. Ordinary math not allowed.
self.val = decimal.Decimal(str(value)) ## Value is precise decimal. Ordinary math not allowed.
self.updateText()
self.skipValidate = False
self.setCorrectionMode(self.CorrectionMode.CorrectToPreviousValue)
@ -181,12 +180,12 @@ class SpinBox(QtGui.QAbstractSpinBox):
elif k == 'max':
self.setMaximum(v, update=False)
elif k in ['step', 'minStep']:
self.opts[k] = decimal.Decimal(asUnicode(v))
self.opts[k] = decimal.Decimal(str(v))
elif k == 'value':
pass ## don't set value until bounds have been set
elif k == 'format':
self.opts[k] = asUnicode(v)
elif k == 'regex' and isinstance(v, basestring):
self.opts[k] = str(v)
elif k == 'regex' and isinstance(v, str):
self.opts[k] = re.compile(v)
elif k in self.opts:
self.opts[k] = v
@ -220,7 +219,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
self.opts['minStep'] = ms
if 'format' not in opts:
self.opts['format'] = asUnicode("{value:d}{suffixGap}{suffix}")
self.opts['format'] = "{value:d}{suffixGap}{suffix}"
if self.opts['dec']:
if self.opts.get('minStep') is None:
@ -234,7 +233,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
def setMaximum(self, m, update=True):
"""Set the maximum allowed value (or None for no limit)"""
if m is not None:
m = decimal.Decimal(asUnicode(m))
m = decimal.Decimal(str(m))
self.opts['bounds'][1] = m
if update:
self.setValue()
@ -242,7 +241,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
def setMinimum(self, m, update=True):
"""Set the minimum allowed value (or None for no limit)"""
if m is not None:
m = decimal.Decimal(asUnicode(m))
m = decimal.Decimal(str(m))
self.opts['bounds'][0] = m
if update:
self.setValue()
@ -298,7 +297,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
Select the numerical portion of the text to allow quick editing by the user.
"""
le = self.lineEdit()
text = asUnicode(le.text())
text = le.text()
m = self.opts['regex'].match(text)
if m is None:
return
@ -358,7 +357,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
value = int(value)
if not isinstance(value, decimal.Decimal):
value = decimal.Decimal(asUnicode(value))
value = decimal.Decimal(str(value))
prev, self.val = self.val, value
changed = not fn.eq(value, prev) # use fn.eq to handle nan
@ -558,9 +557,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
def editingFinishedEvent(self):
"""Edit has finished; set value."""
#print "Edit finished."
if asUnicode(self.lineEdit().text()) == self.lastText:
#print "no text change."
if self.lineEdit().text() == self.lastText:
return
try:
val = self.interpret()
@ -568,10 +565,8 @@ class SpinBox(QtGui.QAbstractSpinBox):
return
if val is False:
#print "value invalid:", str(self.lineEdit().text())
return
if val == self.val:
#print "no value change:", val, self.val
return
self.setValue(val, delaySignal=False) ## allow text update so that values are reformatted pretty-like

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
import numpy as np
from ..Qt import QtGui, QtCore
from ..python2_3 import asUnicode, basestring
from .. import metaarray
translate = QtCore.QCoreApplication.translate
@ -170,7 +169,7 @@ class TableWidget(QtGui.QTableWidget):
Added in version 0.9.9.
"""
if format is not None and not isinstance(format, basestring) and not callable(format):
if format is not None and not isinstance(format, str) and not callable(format):
raise ValueError("Format argument must string, callable, or None. (got %s)" % format)
self._formats[column] = format
@ -203,19 +202,19 @@ class TableWidget(QtGui.QTableWidget):
if isinstance(data, list) or isinstance(data, tuple):
return lambda d: d.__iter__(), None
elif isinstance(data, dict):
return lambda d: iter(d.values()), list(map(asUnicode, data.keys()))
return lambda d: iter(d.values()), list(map(str, data.keys()))
elif (hasattr(data, 'implements') and data.implements('MetaArray')):
if data.axisHasColumns(0):
header = [asUnicode(data.columnName(0, i)) for i in range(data.shape[0])]
header = [str(data.columnName(0, i)) for i in range(data.shape[0])]
elif data.axisHasValues(0):
header = list(map(asUnicode, data.xvals(0)))
header = list(map(str, data.xvals(0)))
else:
header = None
return self.iterFirstAxis, header
elif isinstance(data, np.ndarray):
return self.iterFirstAxis, None
elif isinstance(data, np.void):
return self.iterate, list(map(asUnicode, data.dtype.names))
return self.iterate, list(map(str, data.dtype.names))
elif data is None:
return (None,None)
elif np.isscalar(data):
@ -311,22 +310,22 @@ class TableWidget(QtGui.QTableWidget):
if self.horizontalHeadersSet:
row = []
if self.verticalHeadersSet:
row.append(asUnicode(''))
row.append('')
for c in columns:
row.append(asUnicode(self.horizontalHeaderItem(c).text()))
row.append(self.horizontalHeaderItem(c).text())
data.append(row)
for r in rows:
row = []
if self.verticalHeadersSet:
row.append(asUnicode(self.verticalHeaderItem(r).text()))
row.append(self.verticalHeaderItem(r).text())
for c in columns:
item = self.item(r, c)
if item is not None:
row.append(asUnicode(item.value))
row.append(str(item.value))
else:
row.append(asUnicode(''))
row.append('')
data.append(row)
s = ''
@ -427,7 +426,7 @@ class TableWidgetItem(QtGui.QTableWidgetItem):
Added in version 0.9.9.
"""
if fmt is not None and not isinstance(fmt, basestring) and not callable(fmt):
if fmt is not None and not isinstance(fmt, str) and not callable(fmt):
raise ValueError("Format argument must string, callable, or None. (got %s)" % fmt)
self._format = fmt
self._updateText()
@ -473,7 +472,7 @@ class TableWidgetItem(QtGui.QTableWidgetItem):
else:
return self._format % self.value
else:
return asUnicode(self.value)
return str(self.value)
def __lt__(self, other):
if self.sortMode == 'index' and hasattr(other, 'index'):

View File

@ -1,10 +1,11 @@
# -*- coding: utf-8 -*-
import pyqtgraph as pg
pg.mkQApp()
import pyqtgraph.dockarea as da
def test_dock():
name = pg.asUnicode("évènts_zàhéér")
name = "évènts_zàhéér"
dock = da.Dock(name=name)
# make sure unicode names work correctly
assert dock.name() == name

View File

@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
import sys
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph.parametertree as pt
import pyqtgraph as pg
from pyqtgraph.python2_3 import asUnicode
from pyqtgraph.functions import eq
import numpy as np
@ -44,7 +44,7 @@ def test_types():
all_objs = {
'int0': 0, 'int':7, 'float': -0.35, 'bigfloat': 1e129, 'npfloat': np.float64(5),
'npint': np.int64(5),'npinf': np.inf, 'npnan': np.nan, 'bool': True,
'complex': 5+3j, 'str': '#xxx', 'unicode': asUnicode('µ'),
'complex': 5+3j, 'str': '#xxx', 'unicode': 'µ',
'list': [1,2,3], 'dict': {'1': 2}, 'color': pg.mkColor('k'),
'brush': pg.mkBrush('k'), 'pen': pg.mkPen('k'), 'none': None
}
@ -63,7 +63,7 @@ def test_types():
# str (should be able to make a string out of any type)
types = all_objs.keys()
strtyp = str if sys.version[0] >= '3' else unicode
check_param_types(param.child('str'), strtyp, asUnicode, '', all_objs, types)
check_param_types(param.child('str'), strtyp, str, '', all_objs, types)
# bool (should be able to make a boolean out of any type?)
types = all_objs.keys()

View File

@ -30,7 +30,7 @@ def test_SpinBox_formatting(value, expected_text, opts):
sb.setValue(value)
assert sb.value() == value
assert pg.asUnicode(sb.text()) == expected_text
assert sb.text() == expected_text
@pytest.mark.parametrize("suffix", ["", "V"])

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
import pyqtgraph as pg
import numpy as np
from collections import OrderedDict
@ -112,7 +113,7 @@ def test_TableWidget():
if isinstance(item.value, float):
return "%d %f" % (item.index, item.value)
else:
return pg.asUnicode(item.value)
return str(item.value)
w.setFormat(fmt)
assert isinstance(item.value, float)
assert isinstance(item.index, int)