pyspread.lib package¶
Subpackages¶
- pyspread.lib.packaging package
- pyspread.lib.test package
- Submodules
- pyspread.lib.test.compat module
- pyspread.lib.test.test_array2qimage module
- pyspread.lib.test.test_csv module
- pyspread.lib.test.test_file_helpers module
- pyspread.lib.test.test_hashing module
- pyspread.lib.test.test_qimageview module
- pyspread.lib.test.test_selection module
- test_selection
TestSelection
TestSelection.param_get_absolute_access_string
TestSelection.param_get_bottom_borders_selection
TestSelection.param_test_add
TestSelection.param_test_and
TestSelection.param_test_cell_generator
TestSelection.param_test_contains
TestSelection.param_test_eq
TestSelection.param_test_get_bbox
TestSelection.param_test_get_right_borders_selection
TestSelection.param_test_insert
TestSelection.param_test_nonzero
TestSelection.param_test_shifted
TestSelection.param_test_single_cell_selected
TestSelection.test_add()
TestSelection.test_and()
TestSelection.test_bool()
TestSelection.test_cell_generator()
TestSelection.test_contains()
TestSelection.test_eq()
TestSelection.test_get_absolute_access_string()
TestSelection.test_get_bbox()
TestSelection.test_get_bottom_borders_selection()
TestSelection.test_get_right_borders_selection()
TestSelection.test_insert()
TestSelection.test_repr()
TestSelection.test_shifted()
TestSelection.test_single_cell_selected()
- pyspread.lib.test.test_string_helpers module
- Module contents
Submodules¶
pyspread.lib.attrdict module¶
pyspread.lib.charts module¶
charts¶
Provides matplotlib figure that are chart templates
Provides¶
ChartFigure: Main chart class
- class pyspread.lib.charts.ChartFigure(*attributes)[source]¶
Bases:
Figure
Chart figure class with drawing method
This class is deprecated and exists solely for compatibility with pyspread <1.99.0
- Parameters:
attributes (
List
[dict
]) – List of dicts that contain matplotlib attributes The first list element is defining the axes The following list elements are defining plots
- contour_label_attrs = {'contour_label_colors': 'colors', 'contour_label_fontsize': 'fontsize', 'contour_labels': 'contour_labels'}¶
- contourf_attrs = {'contour_fill': 'contour_fill', 'hatches': 'hatches'}¶
- plot_type_fixed_attrs = {'Sankey': [], 'bar': ['left', 'height'], 'boxplot': ['x'], 'contour': ['X', 'Y', 'Z'], 'contourf': ['X', 'Y', 'Z'], 'hist': ['x'], 'pie': ['x'], 'plot': ['xdata', 'ydata']}¶
- plot_type_xy_mapping = {'Sankey': ['flows', 'orientations'], 'annotate': ['xy', 'xy'], 'bar': ['left', 'height'], 'boxplot': ['x', 'x'], 'contour': ['X', 'Y'], 'contourf': ['X', 'Y', 'Z'], 'hist': ['label', 'x'], 'pie': ['labels', 'x'], 'plot': ['xdata', 'ydata']}¶
- set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, canvas=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, constrained_layout=<UNSET>, constrained_layout_pads=<UNSET>, dpi=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, figheight=<UNSET>, figwidth=<UNSET>, frameon=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, layout_engine=<UNSET>, linewidth=<UNSET>, mouseover=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, size_inches=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, tight_layout=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, zorder=<UNSET>)¶
Set multiple properties at once.
Supported properties are
- Properties:
agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: scalar or None animated: bool canvas: FigureCanvas clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None constrained_layout: unknown constrained_layout_pads: unknown dpi: float edgecolor: color facecolor: color figheight: float figure: ~matplotlib.figure.Figure figwidth: float frameon: bool gid: str in_layout: bool label: object layout_engine: {‘constrained’, ‘compressed’, ‘tight’, ‘none’, .LayoutEngine, None} linewidth: number mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool size_inches: (float, float) or float sketch_params: (scale: float, length: float, randomness: float) snap: bool or None tight_layout: unknown transform: ~matplotlib.transforms.Transform url: str visible: bool zorder: float
pyspread.lib.csv module¶
Provides
sniff()
: Sniffs CSV dialect and header info
- pyspread.lib.csv.csv_reader(csvfile, dialect)[source]¶
Generator of str values from csv file in filepath, ignores header
- pyspread.lib.csv.get_header(csvfile, dialect)[source]¶
Returns list of first line items of file filepath
pyspread.lib.dataclasses module¶
- class pyspread.lib.dataclasses.Field(default, default_factory, init, repr, hash, compare, metadata)[source]¶
Bases:
object
- compare¶
- default¶
- default_factory¶
- hash¶
- init¶
- metadata¶
- name¶
- repr¶
- type¶
- exception pyspread.lib.dataclasses.FrozenInstanceError[source]¶
Bases:
AttributeError
- pyspread.lib.dataclasses.asdict(obj, *, dict_factory=<class 'dict'>)[source]¶
Return the fields of a dataclass instance as a new dictionary mapping field names to field values.
Example usage:
@dataclass class C:
x: int y: int
c = C(1, 2) assert asdict(c) == {‘x’: 1, ‘y’: 2}
If given, ‘dict_factory’ will be used instead of built-in dict. The function applies recursively to field values that are dataclass instances. This will also look into built-in containers: tuples, lists, and dicts.
- pyspread.lib.dataclasses.astuple(obj, *, tuple_factory=<class 'tuple'>)[source]¶
Return the fields of a dataclass instance as a new tuple of field values.
Example usage:
@dataclass class C: x: int y: int
c = C(1, 2) assert astuple(c) == (1, 2)
If given, ‘tuple_factory’ will be used instead of built-in tuple. The function applies recursively to field values that are dataclass instances. This will also look into built-in containers: tuples, lists, and dicts.
- pyspread.lib.dataclasses.dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)[source]¶
Returns the same class as was passed in, with dunder methods added based on the fields defined in the class.
Examines PEP 526 __annotations__ to determine fields.
If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method function is added. If frozen is true, fields may not be assigned to after instance creation.
- pyspread.lib.dataclasses.field(*, default=<pyspread.lib.dataclasses._MISSING_TYPE object>, default_factory=<pyspread.lib.dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None)[source]¶
Return an object to identify dataclass fields.
default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is True, the field will be a parameter to the class’s __init__() function. If repr is True, the field will be included in the object’s repr(). If hash is True, the field will be included in the object’s hash(). If compare is True, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass.
It is an error to specify both default and default_factory.
- pyspread.lib.dataclasses.fields(class_or_instance)[source]¶
Return a tuple describing the fields of this dataclass.
Accepts a dataclass or an instance of one. Tuple elements are of type Field.
- pyspread.lib.dataclasses.is_dataclass(obj)[source]¶
Returns True if obj is a dataclass or an instance of a dataclass.
- pyspread.lib.dataclasses.make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)[source]¶
Return a new dynamically created dataclass.
The dataclass name will be ‘cls_name’. ‘fields’ is an iterable of either (name), (name, type) or (name, type, Field) objects. If type is omitted, use the string ‘typing.Any’. Field objects are created by the equivalent of calling ‘field(name, type [, Field-info])’.
C = make_dataclass(‘C’, [‘x’, (‘y’, int), (‘z’, int, field(init=False))], bases=(Base,))
is equivalent to:
@dataclass class C(Base):
x: ‘typing.Any’ y: int z: int = field(init=False)
For the bases and namespace parameters, see the builtin type() function.
The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to dataclass().
pyspread.lib.exception_handling module¶
exception_handling.py contains functions for handling exceptions generated by user code
Provides
get_user_codeframe()
: Returns traceback that only includes the user’sexecute code frames
- pyspread.lib.exception_handling.get_user_codeframe(tb)[source]¶
Modify traceback to only include the user code’s execution frame Always call in this fashion:
e = sys.exc_info() user_tb = get_user_codeframe(e[2]) or e[2]
so that you can get the original frame back if you need to (this is necessary because copying traceback objects is tricky and this is a good workaround)
- Parameters:
tb (
TracebackType
) – Trace back information- Return type:
pyspread.lib.file_helpers module¶
Provides
- exception pyspread.lib.file_helpers.ProgressDialogCanceled[source]¶
Bases:
Exception
Raised when a progress dialog is canceled
- pyspread.lib.file_helpers.file_progress_gen(main_window, file, title, label, no_lines, step=100)[source]¶
A generator for file iteration that displays a progress bar
Yields (line number, line string). Return value on user cancel via progress dialog is current line number
- Parameters:
- Return type:
- pyspread.lib.file_helpers.linecount(infile, buffer_size=1048576)[source]¶
Count lines in infile
Starts at current position in file. Position is not preserved. Idea taken from https://stackoverflow.com/questions/845058
- pyspread.lib.file_helpers.progress_dialog(main_window, title, label, maximum)[source]¶
contextmanager
that displays a progress dialog- Parameters:
- Return type:
ContextManager
[QProgressDialog
]
pyspread.lib.hashing module¶
File hashing services
Provides
- pyspread.lib.hashing.genkey(nbytes=64)[source]¶
Returns a random byte sting that may be used as signature key
pyspread.lib.qimage2ndarray module¶
The functions in this file are extracted from the project qimage2ndarray https://github.com/hmeine/qimage2ndarray that has been publisched under the BSD-3-Clause License.
Copyright (c) 2009, Hans Meine <hans_meine@gmx.net>
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- pyspread.lib.qimage2ndarray.alpha_view(qimage)[source]¶
Returns alpha view of a given 32-bit color QImage_’s memory.
The result is a 2D numpy.uint8 array, equivalent to byte_view(qimage)[…,3]. The image must have 32 bit pixel size, i.e. be RGB32, ARGB32, or ARGB32_Premultiplied. Note that it is not enforced that the given qimage has a format that actually uses the alpha channel – for Format_RGB32, the alpha channel usually contains 255 everywhere.
For your convenience, qimage may also be a filename, see `Loading and Saving Images`_ in the documentation.
- Parameters:
qimage (QImage_ with 32-bit pixel type) – image whose memory shall be accessed via NumPy
- Return type:
numpy.ndarray_ with shape (height, width) and dtype uint8
- pyspread.lib.qimage2ndarray.array2qimage(array, normalize=False)[source]¶
Convert a 2D or 3D numpy array into a 32-bit QImage_.
The first dimension represents the vertical image axis; the optional third dimension is supposed to contain 1-4 channels:
#channels
interpretation
1
scalar/gray
2
scalar/gray + alpha
3
RGB
4
RGB + alpha
Scalar data will be converted into corresponding gray RGB triples; if you want to convert to an (indexed) 8-bit image instead, use gray2qimage (which cannot support an alpha channel though).
The parameter normalize can be used to normalize an image’s value range to 0..255:
- normalize = (nmin, nmax):
scale & clip image values from nmin..nmax to 0..255
- normalize = nmax:
lets nmin default to zero, i.e. scale & clip the range 0..nmax to 0..255
- normalize = True:
scale image values to 0..255 (same as passing (array.min(), array.max()))
If array contains masked values, the corresponding pixels will be transparent in the result. Thus, the result will be of QImage.Format_ARGB32 if the input already contains an alpha channel (i.e. has shape (H,W,4)) or if there are masked pixels, and QImage.Format_RGB32 otherwise.
- Parameters:
array (2D or 3D numpy.ndarray_ or numpy.ma.array) – image data which should be converted (copied) into a QImage_
normalize (bool, scalar, or pair) – normalization parameter (default: no value changing)
- Return type:
QImage_ with RGB32 or ARGB32 format
- pyspread.lib.qimage2ndarray.byte_view(qimage, byteorder='little')[source]¶
Returns raw 3D view of the given QImage_’s memory.
This will always be a 3-dimensional numpy.ndarray with dtype numpy.uint8.
Note that for 32-bit images, the last dimension will be in the [B,G,R,A] order (if little endian) due to QImage_’s memory layout (the alpha channel will be present for Format_RGB32 images, too).
For 8-bit (indexed) images, the array will still be 3-dimensional, i.e. shape will be (height, width, 1).
The order of channels in the last axis depends on the byteorder, which defaults to ‘little’, i.e. BGRA order. You may set the argument byteorder to ‘big’ to get ARGB, or use None which means sys.byteorder here, i.e. return native order for the machine the code is running on.
For your convenience, qimage may also be a filename, see `Loading and Saving Images`_ in the documentation.
- Parameters:
qimage (QImage_) – image whose memory shall be accessed via NumPy
byteorder – specify order of channels in last axis
- Return type:
numpy.ndarray_ with shape (height, width, 1 or 4) and dtype uint8
- pyspread.lib.qimage2ndarray.rgb_view(qimage, byteorder='big')[source]¶
Returns RGB view of a given 32-bit color QImage_’s memory.
Similarly to byte_view(), the result is a 3D numpy.uint8 array, but reduced to the rgb dimensions (without alpha), and reordered (using negative strides in the last dimension) to have the usual [R,G,B] order. The image must have 32 bit pixel size, i.e. be RGB32, ARGB32, or ARGB32_Premultiplied. (Note that in the latter case, the values are of course premultiplied with alpha.)
The order of channels in the last axis depends on the byteorder, which defaults to ‘big’, i.e. RGB order. You may set the argument byteorder to ‘little’ to get BGR, or use None which means sys.byteorder here, i.e. return native order for the machine the code is running on.
For your convenience, qimage may also be a filename, see `Loading and Saving Images`_ in the documentation.
- Parameters:
qimage (QImage_ with 32-bit pixel type) – image whose memory shall be accessed via NumPy
byteorder – specify order of channels in last axis
- Return type:
numpy.ndarray_ with shape (height, width, 3) and dtype uint8
pyspread.lib.qimage_svg module¶
High resolution svg support for qimage and matplotlib.figure
Provides
pyspread.lib.selection module¶
Grid selection representation
Provides
Selection
: Represents grid selection independently from PyQt
- class pyspread.lib.selection.Selection(block_top_left, block_bottom_right, rows, columns, cells)[source]¶
Bases:
object
Represents grid selection
- Parameters:
- cell_generator(shape, table=None)[source]¶
Returns a generator of cell key tuples
- Parameters:
shape – Grid shape
table – Third component of each returned key
- Return type:
If table is None 2-tuples (row, column) are yielded else 3-tuples
- get_bbox()[source]¶
Returns bounding box
A bounding box is the smallest rectangle that contains all selections. Non-specified boundaries are None.
- get_bottom_borders_selection(border_choice, shape)[source]¶
Get selection of cells, for which the bottom border attributes need to be adjusted on border line and border color changes.
- border_choice names are:
“All borders”
“Top border”
“Bottom border”
“Left border”
“Right border”
“Outer borders”
“Inner borders”
“Top and bottom borders”
- get_grid_bbox(shape)[source]¶
Returns bounding box within grid shape limits
A bounding box is the smallest rectangle that contains all selections. Non-specified boundaries are filled i from size.
- get_relative_access_string(shape, current)[source]¶
Get access string relative to current cell
It is assumed that the selected cells are in the same table as the current cell.
- get_right_borders_selection(border_choice, shape)[source]¶
Get selection of cells, for which the right border attributes need to be adjusted on border line and border color changes.
- border_choice names are:
“All borders”
“Top border”
“Bottom border”
“Left border”
“Right border”
“Outer borders”
“Inner borders”
“Top and bottom borders”
- insert(point, number, axis)[source]¶
Inserts number of rows/columns/tables into selection
Insertion takes place at point on axis.
- property parameters: Tuple[List[Tuple[int, int]], List[Tuple[int, int]], List[int], List[int], List[Tuple[int, int]]]¶
Tuple of selection parameters of self (self.block_tl, self.block_br, self.rows, self.columns,
self.cells)
- Type:
return
pyspread.lib.spelltextedit module¶
Provides
- class pyspread.lib.spelltextedit.LineNumberArea(parent)[source]¶
Bases:
QWidget
- Parameters:
parent (
QPlainTextEdit
) – Editor in which the line numbers shall be displayed
- class pyspread.lib.spelltextedit.PythonEnchantHighlighter(*args)[source]¶
Bases:
QSyntaxHighlighter
QSyntaxHighlighter subclass which consults a PyEnchant dictionary
- braces = ['\\{', '\\}', '\\(', '\\)', '\\[', '\\]']¶
- enable_enchant = False¶
- err_format = <PyQt6.QtGui.QTextCharFormat object>¶
- keywords = ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']¶
- match_multiline(text, delimiter, in_state, style)[source]¶
Do highlighting of multi-line strings.
delimiter
should be a regex for triple-single-quotes or triple-double-quotes, andin_state
should be a unique integer to represent the corresponding state changes when inside those strings. Returns True if we’re still inside a multi-line string when this function is finished.
- operators = ['=', '==', '!=', '<', '<=', '>', '>=', '\\+', '-', '\\*', '/', '//', '\\%', '\\*\\*', '\\+=', '-=', '\\*=', '/=', '\\%=', '\\^', '\\|', '\\&', '\\~', '>>', '<<']¶
- class pyspread.lib.spelltextedit.SpellTextEdit(parent=None, line_numbers=True, font_family='Monospace')[source]¶
Bases:
QPlainTextEdit
QPlainTextEdit subclass which does spell-checking using PyEnchant
- createCorrectionsMenu(cursor, parent=None)[source]¶
Create and return a menu for correcting the selected word.
- createFormatsMenu(parent=None)[source]¶
Create and return a menu for selecting the spell-check language.
- createLanguagesMenu(parent=None)[source]¶
Create and return a menu for selecting the spell-check language.
- createSpellcheckContextMenu(pos)[source]¶
Create and return an augmented default context menu.
This may be used as an alternative to the QPoint-taking form of
createStandardContextMenu
and will work on pre-5.5 Qt.
- cursorForMisspelling(pos)[source]¶
Return a cursor selecting the misspelled word at
pos
orNone
This leverages the fact that QPlainTextEdit already has a system for processing its contents in limited-size blocks to keep things fast.
- max_suggestions = 20¶
- show_line_numbers(visible)[source]¶
Show line number area if visible else hide it
- Parameters:
visible (
bool
) – Line number area visibility
- spaces_per_tab = 4¶
pyspread.lib.string_helpers module¶
Provides
- pyspread.lib.string_helpers.wrap_text(text, width=80, maxlen=2000)[source]¶
Wrap text to line width
- Parameters:
text – The text to be wrapped
width – Width of the text to be wrapped
maxlen – Maximum total text length before text in truncated and extended by […]. If None then truncation is disabled.
- Returns:
Wrapped text
pyspread.lib.typechecks module¶
Functions for checking types and type likeness
Provides