domdf_python_tools
Helpful functions for Python 🐍 🛠️
Docs |
|
---|---|
Tests |
|
PyPI |
|
Anaconda |
|
Activity |
|
QA |
|
Other |
Note
Before version 3 domdf_python_tools
was licensed under the LGPLv3+.
Version 3 and later are licensed under the MIT License.
Installation
python3 -m pip install domdf_python_tools --user
First add the required channels
conda config --add channels https://conda.anaconda.org/conda-forge
conda config --add channels https://conda.anaconda.org/domdfcoding
Then install
conda install domdf_python_tools
python3 -m pip install git+https://github.com/domdfcoding/domdf_python_tools@master --user
Highlights
DelimitedList(iterable = ()
)
Subclass of list
that supports custom delimiters in format strings.
See more in domdf_python_tools.stringlist
.
TemporaryPathPlus( suffix:Optional
[str
] =None
, prefix:Optional
[str
] =None
, dir:Union
[str
,Path
,PathLike
,None
] =None
, )
Securely creates a temporary directory using the same rules as tempfile.mkdtemp()
.
The resulting object can be used as a context manager.
On completion of the context or destruction of the object
the newly created temporary directory and all its contents are removed from the filesystem.
See more in domdf_python_tools.paths
.
StringList( iterable:Iterable
[String
] =()
, convert_indents:bool
=False
, )
A list of strings that represent lines in a multiline string.
See more in domdf_python_tools.stringlist
.
PathPlus(*args, **kwargs)
Subclass of pathlib.Path
with additional methods and a default encoding of UTF-8.
See more in domdf_python_tools.paths
.
Contents
bases
Useful base classes.
Classes:
|
The basic structure of a class that can be converted into a dictionary. |
|
List-like type with fluent methods and some star players. |
|
A list with a name. |
|
Class which simulates a float. |
|
Typed version of |
Data:
Invariant |
|
Invariant |
|
Invariant |
Functions:
|
A factory function to return a custom list subclass with a name. |
Type Variables
-
_F
= TypeVar(_F, bound=UserFloat) Type:
TypeVar
Invariant
TypeVar
bound todomdf_python_tools.bases.UserFloat
.
-
_LU
= TypeVar(_LU, bound=Lineup) Type:
TypeVar
Invariant
TypeVar
bound todomdf_python_tools.bases.Lineup
.
-
_S
= TypeVar(_S, bound=UserList) Type:
TypeVar
Invariant
TypeVar
bound todomdf_python_tools.bases.UserList
.
Dictable
-
class
Dictable
(*args, **kwargs)[source] Bases:
Iterable
[Tuple
[str
,~_V
]]The basic structure of a class that can be converted into a dictionary.
Attributes:
Methods:
__eq__
(other)Return
self == other
.__iter__
()Iterate over the attributes of the class.
__repr__
()Return a string representation of the
Dictable
.__str__
()Return
str(self)
.-
__class_getitem__
= <bound method GenericAlias of <class 'domdf_python_tools.bases.Dictable'>> Type:
MethodType
-
UserList
-
class
UserList
(initlist=None)[source] Bases:
MutableSequence
[~_T
]Typed version of
collections.UserList
.Class that simulates a list. The instance’s contents are kept in a regular list, which is accessible via the
data
attribute ofUserList
instances. The instance’s contents are initially set to a copy of list, defaulting to the empty list[]
.New in version 0.10.0.
- Parameters
initlist (
Optional
[Iterable
[~_T
]]) – The initial values to populate theUserList
with. Default[]
.
Subclassing requirements
Subclasses of
UserList
are expected to offer a constructor which can be called with either no arguments or one argument. List operations which return a new sequence attempt to create an instance of the actual implementation class. To do so, it assumes that the constructor can be called with a single parameter, which is a sequence object used as a data source.If a derived class does not wish to comply with this requirement, all of the special methods supported by this class will need to be overridden; please consult the sources for information about the methods which need to be provided in that case.
Methods:
__add__
(other)Return
self + value
.__contains__
(item)Return
key in self
.__delitem__
(i)Delete
self[key]
.__eq__
(other)Return
self == other
.__ge__
(other)Return
self >= other
.__getitem__
(i)Return
self[key]
.__gt__
(other)Return
self > other
.__le__
(other)Return
self <= other
.__lt__
(other)Return
self < other
.__mul__
(n)Return
self * value
.__radd__
(other)Return
value + self
.__repr__
()Return a string representation of the
UserList
.__rmul__
(n)Return
self * value
.__setitem__
(i, item)Set
self[key]
tovalue
.append
(item)Append
item
to the end of theUserList
.clear
()Remove all items from the
UserList
.copy
()Returns a copy of the
UserList
.count
(item)Returns the number of occurrences of
item
in theUserList
.extend
(other)Extend the
NamedList
by appending elements fromother
.index
(item, *args)Returns the index of the fist element matching
item
.insert
(i, item)Insert
item
at positioni
in theUserList
.pop
([i])Removes and returns the item at index
i
.remove
(item)Removes the first occurrence of
item
from the list.reverse
()Reverse the list in place.
sort
(*[, key, reverse])Sort the list in ascending order and return
None
.Attributes:
A real list object used to store the contents of the
UserList
.-
__class_getitem__
= <bound method GenericAlias of <class 'domdf_python_tools.bases.UserList'>> Type:
MethodType
-
__getitem__
(i)[source] Return
self[key]
.- Return type
- Overloads
__getitem__
(i:int
) ->~_T
__getitem__
(i:slice
) ->MutableSequence
[~_T
]
-
__setitem__
(i, item)[source] Set
self[key]
tovalue
.- Overloads
__setitem__
(i:int
, o:~_T
)__setitem__
(i:slice
, o:Iterable
[~_T
] )
-
index
(item, *args)[source] Returns the index of the fist element matching
item
.- Parameters
item (
~_T
)args
- Raises
ValueError – if the item is not present.
- Return type
-
pop
(i=- 1)[source] Removes and returns the item at index
i
.- Raises
IndexError – if list is empty or index is out of range.
- Return type
-
remove
(item)[source] Removes the first occurrence of
item
from the list.- Parameters
item (
~_T
)- Raises
ValueError – if the item is not present.
-
sort
(*, key=None, reverse=False)[source] Sort the list in ascending order and return
None
.The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
NamedList
Both NamedList
and namedlist()
can be used to create a named list.
namedlist()
can be used as follows:
>>> ShoppingList = namedlist("ShoppingList")
>>> shopping_list = ShoppingList(["egg and bacon", "egg sausage and bacon", "egg and spam", "egg bacon and spam"])
>>>
If you wish to create a subclass with additional features it is recommended to subclass
from NamedList
rather than from namedlist()
. For example, do this:
>>> class ShoppingList(NamedList):
... pass
>>>
and not this:
>>> class ShoppingList(namedlist())
... pass
>>>
This avoids any potential issues with mypy.
-
class
NamedList
(initlist=None)[source] -
A list with a name.
The name of the list is taken from the name of the subclass.
Changed in version 0.10.0:
NamedList
now subclassesUserList
rather thancollections.UserList
.
UserFloat
-
class
UserFloat
(value=0.0)[source] Bases:
Real
Class which simulates a float.
New in version 1.6.0.
- Parameters
value (
Union
[SupportsFloat
,SupportsIndex
,str
,bytes
,bytearray
]) – The values to initialise theUserFloat
with. Default0.0
.
Methods:
__abs__
()Return
abs(self)
.__add__
(other)Return
self + value
.__bool__
()Return
self != 0
.Return
complex(self)
.__divmod__
(other)Return
divmod(self, value)
.__eq__
(other)Return
self == other
.Return
float(self)
.__floordiv__
(other)Return
self // value
.__ge__
(other)Return
self >= other
.__gt__
(other)Return
self > other
.__int__
()Return
int(self)
.__le__
(other)Return
self <= other
.__lt__
(other)Return
self < other
.__mod__
(other)Return
self % value
.__mul__
(other)Return
self * value
.__ne__
(other)Return
self != other
.__neg__
()Return
- self
.__pos__
()Return
+ self
.__pow__
(other[, mod])Return
pow(self, value, mod)
.__radd__
(other)Return
value + self
.__rdivmod__
(other)Return
divmod(value, self)
.__repr__
()Return a string representation of the
UserFloat
.__rfloordiv__
(other)Return
value // self
.__rmod__
(other)Return
value % self
.__rmul__
(other)Return
value * self
.__round__
([ndigits])Round the
UserFloat
tondigits
decimal places, defaulting to0
.__rpow__
(other[, mod])Return
pow(value, self, mod)
.__rsub__
(other)Return
value - self
.__rtruediv__
(other)Return
value / self
.__str__
()Return
str(self)
.__sub__
(other)Return
value - self
.__truediv__
(other)Return
self / value
.Truncates the float to an integer.
Returns the float as a fraction.
fromhex
(string)Create a floating-point number from a hexadecimal string.
hex
()Returns the hexadecimal (base 16) representation of the float.
Returns whether the float is an integer.
-
__complex__
()[source] Return
complex(self)
.complex(self) == complex(float(self), 0)
- Return type
-
__float__
()[source] Return
float(self)
.- Return type
-
__pow__
(other, mod=None)[source] Return
pow(self, value, mod)
.- Return type
-
__round__
(ndigits=None)[source] Round the
UserFloat
tondigits
decimal places, defaulting to0
.If
ndigits
is omitted orNone
, returns anint
, otherwise returns afloat
. Rounds half toward even.
-
__rpow__
(other, mod=None)[source] Return
pow(value, self, mod)
.- Return type
Lineup
-
class
Lineup
(initlist=None)[source] -
List-like type with fluent methods and some star players.
Methods:
append
(item)Append
item
to the end of theUserList
.clear
()Remove all items from the
UserList
.extend
(other)Extend the
NamedList
by appending elements fromother
.insert
(i, item)Insert
item
at positioni
in theUserList
.remove
(item)Removes the first occurrence of
item
from the list.replace
(what, with_)Replace the first instance of
what
withwith_
.reverse
()Reverse the list in place.
sort
(*[, key, reverse])Sort the list in ascending order and return the self.
-
remove
(item)[source] Removes the first occurrence of
item
from the list.- Parameters
item (
~_T
)- Return type
- Raises
ValueError – if the item is not present.
-
sort
(*, key=None, reverse=False)[source] Sort the list in ascending order and return the self.
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
- Return type
-
compat
Cross-version compatibility helpers.
New in version 0.12.0.
Provides the following:
-
importlib_resources
importlib_resources on Python 3.6;
importlib.resources
on Python 3.7 and later.
-
importlib_metadata
importlib_metadata on Python 3.8 and earlier;
importlib.metadata
on Python 3.9 and later.New in version 1.1.0.
Changed in version 2.5.0: importlib_metadata is now used on Python 3.8 in place of the stdlib version.
-
class
nullcontext
(enter_result=None)[source] Bases:
ContextManager
[Optional
[~_T
]]Context manager that does no additional processing.
Used as a stand-in for a normal context manager, when a particular block of code is only sometimes used with a normal context manager:
cm = optional_cm if condition else nullcontext() with cm: # Perform operation, using optional_cm if condition is True
New in version 2.1.0.
In Python 3.7 and above the version from the standard library is used instead of this one, but the implementations are identical.
dates
Utilities for working with dates and times.
Attention
This module has the following additional None:
pytz>=2019.1
This can be installed as follows:
python -m pip install domdf-python-tools[dates]
Data:
Mapping of 3-character shortcodes to full month names. |
|
List of the full names for months in the Gregorian calendar. |
|
List of the short names for months in the Gregorian calendar. |
Functions:
|
Returns the date of Easter in the given year. |
|
Returns |
Returns a tzinfo object for the current timezone. |
|
|
Returns the number of the given month. |
|
Returns a localized |
|
Returns the offset between UTC and the requested timezone on the given date. |
|
Calculates whether the given day falls within British Summer Time. |
|
Converts an integer or shorthand month into the full month name. |
|
Sets the timezone / tzinfo of the given |
|
Convert UTC timestamp (seconds from UNIX epoch) to a |
-
check_date
(month, day, leap_year=True)[source] Returns
True
if the day number is valid for the given month.
-
get_month_number
(month)[source] Returns the number of the given month. If
month
is already a number between 1 and 12 it will be returned immediately.
-
get_timezone
(tz, date=None)[source] Returns a localized
pytz.timezone
object for the given date.If
date
isNone
then the current date is used.
-
get_utc_offset
(tz, date=None)[source] Returns the offset between UTC and the requested timezone on the given date. If
date
isNone
then the current date is used.
-
is_bst
(the_date)[source] Calculates whether the given day falls within British Summer Time.
This function should also be applicable to other timezones which change to summer time on the same date (e.g. Central European Summer Time).
Note
This function does not consider the time of day, and therefore does not handle the fact that the time changes at 1 AM GMT. It also does not account for historic deviations from the current norm.
New in version 3.5.0.
- Parameters
the_date (
Union
[struct_time
,date
]) – Atime.struct_time
,datetime.date
ordatetime.datetime
representing the target date.- Return type
- Returns
True
if the date falls within British Summer Time,False
otherwise.
-
set_timezone
(obj, tzinfo)[source] Sets the timezone / tzinfo of the given
datetime.datetime
object. This will not convert the time (i.e. the hours will stay the same). Usedatetime.datetime.astimezone()
to accomplish that.
-
utc_timestamp_to_datetime
(utc_timestamp, output_tz=None)[source] Convert UTC timestamp (seconds from UNIX epoch) to a
datetime.datetime
object.If
output_tz
isNone
the timestamp is converted to the platform’s local date and time, and the local timezone is inferred and set for the object.If
output_tz
is notNone
, it must be an instance of adatetime.tzinfo
subclass, and the timestamp is converted tooutput_tz
’s time zone.- Parameters
- Return type
- Returns
The timestamp as a datetime object.
- Raises
OverflowError – if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions, and OSError on localtime() or gmtime() failure. It’s common for this to be restricted to years in 1970 through 2038.
-
months
Type:
OrderedDict
[str
,str
]Mapping of 3-character shortcodes to full month names.
Essentially:
months = { Jan="January", Feb="February", Mar="March", Apr="April", May="May", ..., Dec="December", }
delegators
Decorators for functions that delegate parts of their functionality to other functions.
New in version 0.10.0.
Data:
Invariant |
Functions:
|
Decorator to replace |
|
Decorator to replace |
-
_C
= TypeVar(_C, bound=typing.Callable) Type:
TypeVar
Invariant
TypeVar
bound totyping.Callable
.
doctools
Utilities for documenting functions, classes and methods.
Data:
Invariant |
|
Invariant |
Functions:
|
Decorator to appends the docstring from the |
|
Sets the docstring of the |
|
Removes all indentation from the given string. |
|
Sets the docstring of the |
|
Decorator to set the docstring of the |
|
Make proper sphinx links out of double-backticked strings in docstring. |
|
Decorator to prettify the default |
Decorator to make proper sphinx links out of double-backticked strings in the docstring. |
-
_F
= TypeVar(_F, bound=typing.Callable[..., typing.Any]) Type:
TypeVar
Invariant
TypeVar
bound totyping.Callable
[…,typing.Any
].
-
_T
= TypeVar(_T, bound=typing.Type) Type:
TypeVar
Invariant
TypeVar
bound totyping.Type
.
-
append_docstring_from
(original)[source] Decorator to appends the docstring from the
original
function to thetarget
function.This may be useful for subclasses or wrappers that use the same arguments.
Any indentation in either docstring is removed to ensure consistent indentation between the two docstrings. Bear this in mind if additional indentation is used in the docstring.
-
append_doctring_from_another
(target, original)[source] Sets the docstring of the
target
function to that of theoriginal
function.This may be useful for subclasses or wrappers that use the same arguments.
Any indentation in either docstring is removed to ensure consistent indentation between the two docstrings. Bear this in mind if additional indentation is used in the docstring.
-
document_object_from_another
(target, original)[source] Sets the docstring of the
target
function to that of theoriginal
function.This may be useful for subclasses or wrappers that use the same arguments.
-
is_documented_by
(original)[source] Decorator to set the docstring of the
target
function to that of theoriginal
function.This may be useful for subclasses or wrappers that use the same arguments.
-
make_sphinx_links
(input_string, builtins_list=None)[source] Make proper sphinx links out of double-backticked strings in docstring.
i.e.
``str``
becomes:class:`str`
Make sure to include the following in your
conf.py
file for Sphinx:intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}
-
prettify_docstrings
(obj)[source] Decorator to prettify the default
object
docstrings for use in Sphinx documentation.New in version 0.8.0.
getters
Variants of operator.attrgetter()
, operator.itemgetter()
and operator.methodcaller()
which operate on values within sequences.
New in version 3.2.0.
Classes:
|
Returns a callable object that fetches |
|
Returns a callable object that fetches |
|
Returns a callable object that calls the method name on the item at index |
-
class
attrgetter
(idx, attr)[source] Returns a callable object that fetches
attr
from the item at indexidx
in its operand.The attribute name can contain dots. For example:
After
f = attrgetter(0, 'name')
, the call callf(b)
returnsb[0].name
.After
f = attrgetter(3, 'name.first')
, the callf(b)
returnsb[3].name.first
.
>>> from pathlib import Path >>> attrgetter(0, 'name')([Path("dir/code.py")]) 'code.py' >>> attrgetter(2, 'parent.name')([Path("dir/coincidence.py"), Path("dir/wheel.py"), Path("dir/operator.py")]) 'dir'
See also
-
class
itemgetter
(idx, item)[source] Returns a callable object that fetches
item
from the item at indexidx
in its operand, using the__getitem__()
method.For example:
After
f = itemgetter(0, 2)
, the call callf(r)
returnsr[0][2]
.After
g = itemgetter(3, 5)
, the callg(r)
returnsr[3][5]
.
The items can be any type accepted by the item’s
__getitem__()
method. Dictionaries accept any hashable value. Lists, tuples, and strings accept an index or a slice:>>> itemgetter(0, 1)(['ABCDEFG']) 'B' >>> itemgetter(1, 2)(['ABC', 'DEF']) 'F' >>> itemgetter(0, slice(2, None))(['ABCDEFG']) 'CDEFG' >>> army = [dict(rank='captain', name='Blackadder'), dict(rank='Private', name='Baldrick')] >>> itemgetter(0, 'rank')(army) 'captain'
See also
-
class
methodcaller
(_idx, _name, *args, **kwargs)[source] Returns a callable object that calls the method name on the item at index
idx
in its operand.If additional arguments and/or keyword arguments are given, they will be passed to the method as well. For example:
After
f = methodcaller(0, 'name')
, the callf(b)
returnsb[0].name()
.After
f = methodcaller(1, 'name', 'foo', bar=1)
, the callf(b)
returnsb[1].name('foo', bar=1)
.
>>> from datetime import date >>> methodcaller(0, 'upper')(["hello", "world"]) 'HELLO' >>> methodcaller(1, 'center', 9, "=")(["hello", "world"]) '==world==' >>> methodcaller(0, 'replace', year=2019)([date(2021, 7, 6)]) datetime.date(2019, 7, 6)
See also
- Parameters
_idx – The index of the item to call the method on.
_attr – The name of the method to call.
*args – Positional arguments to pass to the method.
**kwargs – Keyword arguments to pass to the method.
import_tools
Functions for importing classes.
New in version 0.5.0.
Functions:
|
Returns a list of objects in the given package, optionally filtered by |
|
Returns a list of entry points in the given category, optionally filtered by |
|
Returns a mapping of entry point names to the entry points in the given category, optionally filtered by |
|
Returns a list of objects in the given module, optionally filtered by |
|
Returns an iterator over the names of the submodules and subpackages of the given module. |
-
discover
(package, match_func=None, exclude_side_effects=True)[source] Returns a list of objects in the given package, optionally filtered by
match_func
.- Parameters
package (
ModuleType
) – A Python packagematch_func (
Optional
[Callable
[[Any
],bool
]]) – Function taking an object and returningTrue
if the object is to be included in the output. DefaultNone
, which includes all objects.exclude_side_effects (
bool
) – Don’t include objects that are only there because of an import side effect. DefaultTrue
.
- Return type
- Overloads
Changed in version 1.0.0: Added the
exclude_side_effects
parameter.
-
discover_entry_points
(group_name, match_func=None)[source] Returns a list of entry points in the given category, optionally filtered by
match_func
.New in version 1.1.0.
- Parameters
- Return type
- Returns
List of matching objects.
-
discover_entry_points_by_name
(group_name, name_match_func=None, object_match_func=None)[source] Returns a mapping of entry point names to the entry points in the given category, optionally filtered by
name_match_func
andobject_match_func
.New in version 2.5.0.
- Parameters
group_name (
str
) – The entry point group name, e.g.'entry_points'
.name_match_func (
Optional
[Callable
[[Any
],bool
]]) – Function taking the entry point name and returningTrue
if the entry point is to be included in the output. DefaultNone
, which includes all entry points.object_match_func (
Optional
[Callable
[[Any
],bool
]]) – Function taking an object and returningTrue
if the object is to be included in the output. DefaultNone
, which includes all objects.
- Return type
-
discover_in_module
(module, match_func=None, exclude_side_effects=True)[source] Returns a list of objects in the given module, optionally filtered by
match_func
.New in version 2.6.0.
- Parameters
module (
ModuleType
) – A Python module.match_func (
Optional
[Callable
[[Any
],bool
]]) – Function taking an object and returningTrue
if the object is to be included in the output. DefaultNone
, which includes all objects.exclude_side_effects (
bool
) – Don’t include objects that are only there because of an import side effect. DefaultTrue
.
- Return type
iterative
Functions for iteration, looping etc.
New in version 1.4.0.
Data:
Functions:
|
Shorthand for |
|
Yield successive |
|
Make an iterator which returns evenly spaced values starting with number |
|
Flatten a list of lists of lists into a single list. |
|
Extend |
|
Extend |
|
Extend |
|
Flattens a mixed list of primitive types and iterables of those types into a single list, regardless of nesting. |
|
Returns an iterator over the discrete ranges of values in |
|
Returns the string representation of a mixed list of strings and lists of strings, similar to tree(1). |
|
Returns the maximum value from |
|
Returns the minimum value from |
|
Return permutations containing |
|
Returns an iterator over the minimum and maximum values for each discrete ranges of values in |
|
Split |
-
Len
(obj, start=0, step=1)[source] Shorthand for
range(len(obj))
.Returns an object that produces a sequence of integers from
start
(inclusive) tolen(obj)
(exclusive) bystep
.New in version 0.4.7.
- Parameters
- Return type
Changed in version 1.4.0: Moved from
domdf_python_tools.utils
-
chunks
(l, n)[source] Yield successive
n
-sized chunks froml
.- Parameters
- Return type
Changed in version 1.4.0: Moved from
domdf_python_tools.utils
-
count
(start=0, step=1)[source] Make an iterator which returns evenly spaced values starting with number
start
.Often used as an argument to
map()
to generate consecutive data points. Can also be used withzip()
to add sequence numbers.New in version 2.7.0.
- Parameters
- Return type
See also
The difference is that this returns more exact floats, whereas the values from
itertools.count()
drift.A demonstration of the drift can be seen in this file:
count_demo.py
.
-
double_chain
(iterable)[source] Flatten a list of lists of lists into a single list.
Literally just:
chain.from_iterable(chain.from_iterable(iterable))
Will convert
[[(1, 2), (3, 4)], [(5, 6), (7, 8)]]
to
[1, 2, 3, 4, 5, 6, 7, 8]
New in version 0.4.7.
- Parameters
iterable (
Iterable
[Iterable
[Iterable
[~_T
]]]) – The iterable to chain.- Return type
Iterator
[~_T
]
Changed in version 1.4.0: Moved from
domdf_python_tools.utils
-
extend
(sequence, minsize)[source] Extend
sequence
by repetition until it is at least as long asminsize
.New in version 2.3.0.
See also
-
extend_with
(sequence, minsize, with_)[source] Extend
sequence
by addingwith\_
to the right hand end until it is at least as long asminsize
.New in version 2.3.0.
See also
-
extend_with_none
(sequence, minsize)[source] Extend
sequence
by addingNone
to the right hand end until it is at least as long asminsize
.New in version 2.3.0.
See also
-
flatten
(iterable, primitives=(<class 'str'>, <class 'int'>, <class 'float'>))[source] Flattens a mixed list of primitive types and iterables of those types into a single list, regardless of nesting.
New in version 1.4.0.
-
groupfloats
(iterable, step=1)[source] Returns an iterator over the discrete ranges of values in
iterable
.For example:
>>> list(groupfloats( ... [170.0, 170.05, 170.1, 170.15, 171.05, 171.1, 171.15, 171.2], ... step=0.05, ... )) [(170.0, 170.05, 170.1, 170.15), (171.05, 171.1, 171.15, 171.2)] >>> list(groupfloats([1, 2, 3, 4, 5, 7, 8, 9, 10])) [(1, 2, 3, 4, 5), (7, 8, 9, 10)]
New in version 2.0.0.
- Parameters
- Return type
See also
ranges_from_iterable()
, which returns an iterator over the min and max values for each range.
-
make_tree
(tree)[source] Returns the string representation of a mixed list of strings and lists of strings, similar to tree(1).
New in version 1.4.0.
-
natmax
(seq, key=None, alg=<ns.DEFAULT: 0>)[source] Returns the maximum value from
seq
when sorted naturally.New in version 1.8.0.
- Parameters
seq (
Iterable
[~_T
])key (
Optional
[Callable
[[Any
],Any
]]) – A key used to determine how to sort each element of the iterable. It is not applied recursively. The callable should accept a single argument and return a single value. DefaultNone
.alg (
int
) – This option is used to control which algorithmnatsort
uses when sorting. Default<ns.DEFAULT: 0>
.
- Return type
~_T
-
natmin
(seq, key=None, alg=<ns.DEFAULT: 0>)[source] Returns the minimum value from
seq
when sorted naturally.New in version 1.8.0.
- Parameters
seq (
Iterable
[~_T
])key (
Optional
[Callable
[[Any
],Any
]]) – A key used to determine how to sort each element of the iterable. It is not applied recursively. The callable should accept a single argument and return a single value. DefaultNone
.alg (
int
) – This option is used to control which algorithmnatsort
uses when sorting. Default<ns.DEFAULT: 0>
.
- Return type
~_T
-
permutations
(data, n=2)[source] Return permutations containing
n
items fromdata
without any reverse duplicates.If
n
is equal to or greater than the length of the data an empty list of returned.Changed in version 1.4.0: Moved from
domdf_python_tools.utils
See also
-
ranges_from_iterable
(iterable, step=1)[source] Returns an iterator over the minimum and maximum values for each discrete ranges of values in
iterable
.For example:
>>> list(ranges_from_iterable([170.0, 170.05, 170.1, 170.15, 171.05, 171.1, 171.15, 171.2], step=0.05)) [(170.0, 170.15), (171.05, 171.2)] >>> list(ranges_from_iterable([1, 2, 3, 4, 5, 7, 8, 9, 10])) [(1, 5), (7, 10)]
paths
Functions for paths and files.
Changed in version 1.0.0: Removed relpath2
.
Use domdf_python_tools.paths.relpath()
instead.
Classes:
|
Compare the content of |
|
Subclass of |
|
|
|
Securely creates a temporary directory using the same rules as |
|
|
Data:
Invariant |
|
Invariant |
|
A list of directories which will likely be unwanted when searching directory trees for files. |
Functions:
|
Append |
|
Write string to |
|
Compare the content of two directory trees. |
|
Alternative to |
|
Delete the file in the current directory. |
|
Context manager to change into the given directory for the duration of the |
|
Make the given file executable. |
|
Given a filename and a glob pattern, return whether the filename matches the glob. |
|
Create a directory at the given path, but only if the directory does not already exist. |
|
Returns the path of the parent directory for the given file or directory. |
|
Read a file in the current directory (in text mode). |
|
Returns the path for the given file or directory relative to the given directory or, if that would require path traversal, returns the absolute path. |
|
Sort the |
|
Traverse the parents of the given directory until the desired file is found. |
|
Write a variable to file in the current directory. |
-
class
DirComparator
(a, b, ignore=None, hide=None)[source] Bases:
dircmp
Compare the content of
a
anda
.In contrast with
filecmp.dircmp
, this subclass compares the content of files with the same path.New in version 2.7.0.
- Parameters
a (
Union
[str
,Path
,PathLike
]) – The “left” directory to compare.b (
Union
[str
,Path
,PathLike
]) – The “right” directory to compare.ignore (
Optional
[Sequence
[str
]]) – A list of names to ignore. Defaultfilecmp.DEFAULT_IGNORES
.hide (
Optional
[Sequence
[str
]]) – A list of names to hide. Default[
os.curdir
,os.pardir
]
.
-
class
PathPlus
(*args, **kwargs)[source] Bases:
Path
Subclass of
pathlib.Path
with additional methods and a default encoding of UTF-8.Path represents a filesystem path but, unlike
pathlib.PurePath
, also offers methods to do system calls on path objects. Depending on your system, instantiating aPathPlus
will return either aPosixPathPlus
or aWindowsPathPlus
. object. You can also instantiate aPosixPathPlus
orWindowsPath
directly, but cannot instantiate aWindowsPathPlus
on a POSIX system or vice versa.New in version 0.3.8.
Changed in version 0.5.1: Defaults to Unix line endings (
LF
) on all platforms.Methods:
abspath
()Return the absolute version of the path.
append_text
(string[, encoding, errors])Open the file in text mode, append the given string to it, and close the file.
dump_json
(data[, encoding, errors, …])Dump
data
to the file as JSON.from_uri
(uri)Construct a
PathPlus
from afile
URI returned bypathlib.PurePath.as_uri()
.iterchildren
([exclude_dirs, match, matchcase])Returns an iterator over all children (files and directories) of the current path object.
load_json
([encoding, errors, json_library, …])Load JSON data from the file.
Make the file executable.
maybe_make
([mode, parents])Create a directory at this path, but only if the directory does not already exist.
move
(dst)Recursively move
self
todst
.open
([mode, buffering, encoding, errors, …])Open the file pointed by this path and return a file object, as the built-in
open()
function does.read_lines
([encoding, errors])Open the file in text mode, return a list containing the lines in the file, and close the file.
read_text
([encoding, errors])Open the file in text mode, read it, and close the file.
stream
([chunk_size])Stream the file in
chunk_size
sized chunks.write_clean
(string[, encoding, errors])Write to the file without trailing whitespace, and with a newline at the end of the file.
write_lines
(data[, encoding, errors, …])Write the given list of lines to the file without trailing whitespace.
write_text
(data[, encoding, errors, newline])Open the file in text mode, write to it, and close the file.
-
append_text
(string, encoding='UTF-8', errors=None)[source] Open the file in text mode, append the given string to it, and close the file.
New in version 0.3.8.
-
dump_json
(data, encoding='UTF-8', errors=None, json_library=<module 'json'>, *, compress=False, **kwargs)[source] Dump
data
to the file as JSON.New in version 0.5.0.
- Parameters
data (
Any
) – The object to serialise to JSON.encoding (
Optional
[str
]) – The encoding to write to the file in. Default'UTF-8'
.json_library (
JsonLibrary
) – The JSON serialisation library to use. Defaultjson
.compress (
bool
) – Whether to compress the JSON file using gzip. DefaultFalse
.**kwargs – Keyword arguments to pass to the JSON serialisation function.
Changed in version 1.0.0: Now uses
PathPlus.write_clean
rather thanPathPlus.write_text
, and as a result returnsNone
rather thanint
.Changed in version 1.9.0: Added the
compress
keyword-only argument.
-
classmethod
from_uri
(uri)[source] Construct a
PathPlus
from afile
URI returned bypathlib.PurePath.as_uri()
.New in version 2.9.0.
-
iterchildren
(exclude_dirs=('.git', '.hg', 'venv', '.venv', '.mypy_cache', '__pycache__', '.pytest_cache', '.tox', '.tox4', '.nox', '__pypackages__'), match=None, matchcase=True)[source] Returns an iterator over all children (files and directories) of the current path object.
New in version 2.3.0.
- Parameters
exclude_dirs (
Optional
[Iterable
[str
]]) – A list of directory names which should be excluded from the output, together with their children. Default('.git', '.hg', 'venv', '.venv', '.mypy_cache', '__pycache__', '.pytest_cache', '.tox', '.tox4', '.nox', '__pypackages__')
.match (
Optional
[str
]) – A pattern to match filenames against. The pattern should be in the format taken bymatchglob()
. DefaultNone
.matchcase (
bool
) – Whether the filename’s case should match the pattern. DefaultTrue
.
- Return type
Changed in version 2.5.0: Added the
matchcase
option.
-
load_json
(encoding='UTF-8', errors=None, json_library=<module 'json'>, *, decompress=False, **kwargs)[source] Load JSON data from the file.
New in version 0.5.0.
- Parameters
encoding (
Optional
[str
]) – The encoding to write to the file in. Default'UTF-8'
.json_library (
JsonLibrary
) – The JSON serialisation library to use. Defaultjson
.decompress (
bool
) – Whether to decompress the JSON file using gzip. Will raise an exception if the file is not compressed. DefaultFalse
.**kwargs – Keyword arguments to pass to the JSON deserialisation function.
- Return type
- Returns
The deserialised JSON data.
Changed in version 1.9.0: Added the
compress
keyword-only argument.
-
maybe_make
(mode=511, parents=False)[source] Create a directory at this path, but only if the directory does not already exist.
New in version 0.3.8.
- Parameters
mode (
int
) – Combined with the process’ umask value to determine the file mode and access flags. Default511
.parents (
bool
) – IfFalse
(the default), a missing parent raises aFileNotFoundError
. IfTrue
, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).
Changed in version 1.6.0: Removed the
'exist_ok'
option, since it made no sense in this context.Attention
This will fail silently if a file with the same name already exists. This appears to be due to the behaviour of
os.mkdir()
.
-
move
(dst)[source] Recursively move
self
todst
.self
may be a file or a directory.See
shutil.move()
for more details.New in version 3.2.0.
-
open
(mode='r', buffering=- 1, encoding='UTF-8', errors=None, newline=NEWLINE_DEFAULT)[source] Open the file pointed by this path and return a file object, as the built-in
open()
function does.New in version 0.3.8.
- Parameters
- Return type
Changed in version 0.5.1: Defaults to Unix line endings (
LF
) on all platforms.
-
read_lines
(encoding='UTF-8', errors=None)[source] Open the file in text mode, return a list containing the lines in the file, and close the file.
New in version 0.5.0.
-
read_text
(encoding='UTF-8', errors=None)[source] Open the file in text mode, read it, and close the file.
New in version 0.3.8.
-
stream
(chunk_size=1024)[source] Stream the file in
chunk_size
sized chunks.- Parameters
chunk_size (
int
) – The chunk size, in bytes. Default1024
.
New in version 3.2.0.
-
write_clean
(string, encoding='UTF-8', errors=None)[source] Write to the file without trailing whitespace, and with a newline at the end of the file.
New in version 0.3.8.
-
write_lines
(data, encoding='UTF-8', errors=None, *, trailing_whitespace=False)[source] Write the given list of lines to the file without trailing whitespace.
New in version 0.5.0.
- Parameters
Changed in version 2.4.0: Added the
trailing_whitespace
option.
-
write_text
(data, encoding='UTF-8', errors=None, newline=NEWLINE_DEFAULT)[source] Open the file in text mode, write to it, and close the file.
New in version 0.3.8.
- Parameters
Changed in version 3.1.0: Added the
newline
argument to match Python 3.10. (see python/cpython#22420python/cpython#22420)- Return type
-
-
class
PosixPathPlus
(*args, **kwargs)[source] Bases:
PathPlus
,PurePosixPath
PathPlus
subclass for non-Windows systems.On a POSIX system, instantiating a
PathPlus
object should return an instance of this class.New in version 0.3.8.
-
class
TemporaryPathPlus
(suffix=None, prefix=None, dir=None)[source] Bases:
TemporaryDirectory
Securely creates a temporary directory using the same rules as
tempfile.mkdtemp()
. The resulting object can be used as a context manager. On completion of the context or destruction of the object the newly created temporary directory and all its contents are removed from the filesystem.Unlike
tempfile.TemporaryDirectory()
this class is based around aPathPlus
object.New in version 2.4.0.
Methods:
cleanup
()Cleanup the temporary directory by removing it and its contents.
Attributes:
The temporary directory itself.
-
cleanup
()[source] Cleanup the temporary directory by removing it and its contents.
If the
TemporaryPathPlus
is used as a context manager this is called when leaving thewith
block.
-
name
Type:
PathPlus
The temporary directory itself.
This will be assigned to the target of the
as
clause if theTemporaryPathPlus
is used as a context manager.
-
-
class
WindowsPathPlus
(*args, **kwargs)[source] Bases:
PathPlus
,PureWindowsPath
PathPlus
subclass for Windows systems.On a Windows system, instantiating a
PathPlus
object should return an instance of this class.New in version 0.3.8.
The following methods are unsupported on Windows:
-
_P
= TypeVar(_P, bound=Path) Type:
TypeVar
Invariant
TypeVar
bound topathlib.Path
.New in version 0.11.0.
Changed in version 1.7.0: Now bound to
pathlib.Path
.
-
_PP
= TypeVar(_PP, bound=PathPlus) Type:
TypeVar
Invariant
TypeVar
bound todomdf_python_tools.paths.PathPlus
.New in version 2.3.0.
-
copytree
(src, dst, symlinks=False, ignore=None)[source] Alternative to
shutil.copytree()
to support copying to a directory that already exists.Based on https://stackoverflow.com/a/12514470 by https://stackoverflow.com/users/23252/atzz
In Python 3.8 and above
shutil.copytree()
takes adirs_exist_ok
argument, which has the same result.- Parameters
dst (
Union
[str
,Path
,PathLike
]) – Destination to copy file tosymlinks (
bool
) – Whether to represent symbolic links in the source as symbolic links in the destination. If false or omitted, the contents and metadata of the linked files are copied to the new tree. When symlinks is false, if the file pointed by the symlink doesn’t exist, an exception will be added in the list of errors raised in an Error exception at the end of the copy process. You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Notice that this option has no effect on platforms that don’t supportos.symlink()
. DefaultFalse
.ignore (
Optional
[Callable
]) – A callable that will receive as its arguments the source directory, and a list of its contents. The ignore callable will be called once for each directory that is copied. The callable must return a sequence of directory and file names relative to the current directory (i.e. a subset of the items in its second argument); these names will then be ignored in the copy process.shutil.ignore_patterns()
can be used to create such a callable that ignores names based on glob-style patterns. DefaultNone
.
- Return type
-
in_directory
(directory)[source] Context manager to change into the given directory for the duration of the
with
block.
-
matchglob
(filename, pattern, matchcase=True)[source] Given a filename and a glob pattern, return whether the filename matches the glob.
New in version 2.3.0.
- Parameters
- Return type
See also
Glob (programming)#Syntax on Wikipedia
Changed in version 2.5.0: Added the
matchcase
option.
-
maybe_make
(directory, mode=511, parents=False)[source] Create a directory at the given path, but only if the directory does not already exist.
Attention
This will fail silently if a file with the same name already exists. This appears to be due to the behaviour of
os.mkdir()
.- Parameters
directory (
Union
[str
,Path
,PathLike
]) – Directory to createmode (
int
) – Combined with the process’s umask value to determine the file mode and access flags. Default511
.parents (
bool
) – IfFalse
(the default), a missing parent raises aFileNotFoundError
. IfTrue
, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIXmkdir -p
command).
Changed in version 1.6.0: Removed the
'exist_ok'
option, since it made no sense in this context.
-
parent_path
(path)[source] Returns the path of the parent directory for the given file or directory.
-
relpath
(path, relative_to=None)[source] Returns the path for the given file or directory relative to the given directory or, if that would require path traversal, returns the absolute path.
-
traverse_to_file
(base_directory, *filename, height=- 1)[source] Traverse the parents of the given directory until the desired file is found.
New in version 1.7.0.
-
unwanted_dirs
= ('.git', '.hg', 'venv', '.venv', '.mypy_cache', '__pycache__', '.pytest_cache', '.tox', '.tox4', '.nox', '__pypackages__') Type:
tuple
A list of directories which will likely be unwanted when searching directory trees for files.
New in version 2.3.0.
Changed in version 2.9.0: Added
.hg
(mercurial)Changed in version 3.0.0: Added
__pypackages__
(PEP 582)Changed in version 3.2.0: Added
.nox
(https://nox.thea.codes/)
pretty_print
Functions and classes for pretty printing.
New in version 0.10.0.
Classes:
|
Subclass of |
Functions:
|
Adds a simple |
-
class
FancyPrinter
(indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True)[source] Bases:
PrettyPrinter
Subclass of
PrettyPrinter
with different formatting.- Parameters
indent (
int
) – Number of spaces to indent for each level of nesting. Default1
.width (
int
) – Attempted maximum number of columns in the output. Default80
.depth (
Optional
[int
]) – The maximum depth to print out nested structures. DefaultNone
.stream (
Optional
[IO
[str
]]) – The desired output stream. If omitted (orFalse
), the standard output stream available at construction will be used. DefaultNone
.compact (
bool
) – IfTrue
, several items will be combined in one line. DefaultFalse
.sort_dicts (
bool
) – IfTrue
, dict keys are sorted. Only takes effect on Python 3.8 and later, or if pprint36 is installed. DefaultTrue
.
-
simple_repr
(*attributes, show_module=False, **kwargs)[source] Adds a simple
__repr__
method to the decorated class.- Parameters
attributes – The attributes to include in the
__repr__
.show_module (
bool
) – Whether to show the name of the module in the__repr__
. DefaultFalse
.**kwargs – Keyword arguments passed on to
pprint.PrettyPrinter
.
secrets
Functions for working with secrets, such as API tokens.
New in version 0.4.6.
Classes:
|
Subclass of |
-
class
Secret
(value)[source] Bases:
str
Subclass of
str
that guards against accidentally printing a secret to the terminal.The actual value of the secret is accessed via the
.value
attribute.The protection should be maintained even when the secret is in a list, tuple, set or dict, but you should still refrain from printing objects containing the secret.
The secret overrides the
__eq__()
method ofstr
, so:>>> Secret("Barry as FLUFL") == "Barry as FLUFL" True
New in version 0.4.6.
Methods:
__eq__
(other)Return
self == other
.Attributes:
The actual value of the secret.
stringlist
A list of strings that represent lines in a multiline string.
Changed in version 1.0.0: String
should now be imported from domdf_python_tools.typing
.
Classes:
|
Subclass of |
|
Represents an indent, having a symbol/type and a size. |
|
A list of strings that represent lines in a multiline string. |
Data:
Invariant |
Functions:
|
Given a list of two-element tuples, each containing a line and a newline character (or empty string), return a single string. |
|
Split |
-
class
DelimitedList
(iterable=(), /)[source] Bases:
List
[~_S
]Subclass of
list
that supports custom delimiters in format strings.Example:
>>> l = DelimitedList([1, 2, 3, 4, 5]) >>> format(l, ", ") '1, 2, 3, 4, 5' >>> f"Numbers: {l:, }" 'Numbers: 1, 2, 3, 4, 5'
New in version 1.1.0.
-
class
Indent
(size=0, type='\t')[source] Bases:
object
Represents an indent, having a symbol/type and a size.
- Parameters
Methods:
__eq__
(other)Return
self == other
.__iter__
()Returns the size and type of the
Indent
.__repr__
()Returns the string representation of the
Indent
.__str__
()Returns the
Indent
as a string.Attributes:
The indent size.
The indent character.
-
class
StringList
(iterable=(), convert_indents=False)[source] -
A list of strings that represent lines in a multiline string.
- Parameters
Methods:
Returns the
StringList
as bytes.__eq__
(other)Returns whether the other object is equal to this
StringList
.__getitem__
(index)Returns the line with the given index.
__setitem__
(index, line)Replaces the given line with new content.
__str__
()Returns the
StringList
as a string.append
(line)Append a line to the end of the
StringList
.blankline
([ensure_single])Append a blank line to the end of the
StringList
.copy
()Returns a shallow copy of the
StringList
.Returns a count of the blank lines in the
StringList
.extend
(iterable)Extend the
StringList
with lines fromiterable
.insert
(index, line)Insert a line into the
StringList
at the given position.set_indent
(indent[, size])Sets the indent to insert at the beginning of new lines.
set_indent_size
([size])Sets the size of the indent to insert at the beginning of new lines.
set_indent_type
([indent_type])Sets the type of the indent to insert at the beginning of new lines.
splitlines
([keepends])Analagous to
str.splitlines()
.with_indent
(indent[, size])Context manager to temporarily use a different indent.
with_indent_size
([size])Context manager to temporarily use a different indent size.
with_indent_type
([indent_type])Context manager to temporarily use a different indent type.
Attributes:
Whether indents at the start of lines should be converted.
The indent to insert at the beginning of new lines.
The current indent size.
The current indent type.
-
__bytes__
()[source] Returns the
StringList
as bytes.New in version 2.1.0.
- Return type
-
__eq__
(other)[source] Returns whether the other object is equal to this
StringList
.- Return type
-
__getitem__
(index)[source] Returns the line with the given index.
- Parameters
index (
Union
[SupportsIndex
,slice
])- Return type
- Overloads
__getitem__
(index:SupportsIndex
) ->str
__getitem__
(index:slice
) ->~_SL
Changed in version 1.8.0: Now returns a
StringList
whenindex
is aslice
.Changed in version 3.2.0: Changed
int
in the type annotation toSupportsIndex
.
-
__setitem__
(index, line)[source] Replaces the given line with new content.
If the new content consists of multiple lines subsequent content in the
StringList
will be shifted down.Changed in version 3.2.0: Changed
int
in the type annotation toSupportsIndex
.- Overloads
__setitem__
(index:SupportsIndex
, line:String
) ->None
__setitem__
(index:slice
, line:Iterable
[String
] ) ->None
-
__str__
()[source] Returns the
StringList
as a string.- Return type
-
append
(line)[source] Append a line to the end of the
StringList
.- Parameters
line (
String
)
-
blankline
(ensure_single=False)[source] Append a blank line to the end of the
StringList
.
-
convert_indents
Type:
bool
Whether indents at the start of lines should be converted.
Only applies to lines added after this is enabled/disabled.
Can only be used when the indent is
'\t'
or'␣'
.
-
copy
()[source] Returns a shallow copy of the
StringList
.Equivalent to
a[:]
.- Return type
-
count_blanklines
()[source] Returns a count of the blank lines in the
StringList
.New in version 0.7.1.
- Return type
-
extend
(iterable)[source] Extend the
StringList
with lines fromiterable
.- Parameters
iterable (
Iterable
[String
]) – An iterable of string-like objects to add to the end of theStringList
.
-
insert
(index, line)[source] Insert a line into the
StringList
at the given position.- Parameters
index (
SupportsIndex
)line (
String
)
Changed in version 3.2.0: Changed
int
in the type annotation toSupportsIndex
.
-
set_indent_size
(size=0)[source] Sets the size of the indent to insert at the beginning of new lines.
- Parameters
size (
int
) – The indent size to use for new lines. Default0
.
-
set_indent_type
(indent_type='\t')[source] Sets the type of the indent to insert at the beginning of new lines.
- Parameters
indent_type (
str
) – The type of indent to use for new lines. Default'\t'
.
-
splitlines
(keepends=False)[source] Analagous to
str.splitlines()
.New in version 3.8.0.
-
with_indent
(indent, size=0)[source] Context manager to temporarily use a different indent.
>>> sl = StringList() >>> with sl.with_indent(" ", 1): ... sl.append("Hello World")
-
splitlines
(string)[source] Split
string
into a list of two-element tuples, containing the line content and the newline character(s), if any.New in version 3.2.0.
See also
-
joinlines
(lines)[source] Given a list of two-element tuples, each containing a line and a newline character (or empty string), return a single string.
New in version 3.2.0.
See also
-
_SL
= TypeVar(_SL, bound=StringList) Type:
TypeVar
Invariant
TypeVar
bound todomdf_python_tools.stringlist.StringList
.
terminal
Useful functions for terminal-based programs.
Changed in version 2.0.0: domdf_python_tools.terminal.get_terminal_size()
was removed.
Use shutil.get_terminal_size()
instead.
Classes:
|
Context manager for echoing variable assignments (in CPython). |
Functions:
|
Prints a blank line. |
|
Clears the display. |
Print the key combination needed to abort the script; dynamic depending on OS. |
|
|
Print |
-
class
Echo
(indent=' ')[source] Bases:
object
Context manager for echoing variable assignments (in CPython).
- Parameters
indent (
str
) – The indentation of the dictionary of variable assignments. Default'␣␣'
.
Methods:
Called when entering the context manager.
__exit__
(*args, **kwargs)Called when exiting the context manager.
-
clear
()[source] Clears the display.
Works for Windows and POSIX, but does not clear the Python Interpreter or PyCharm’s Console.
-
interrupt
()[source] Print the key combination needed to abort the script; dynamic depending on OS.
Useful when you have a long-running script that you might want to interrupt part way through.
Example:
>>> interrupt() (Press Ctrl-C to quit at any time)
-
overtype
(*objects, sep=' ', end='', file=None, flush=False)[source] Print
*objects
to the text streamfile
, starting with'\\r'
, separated bysep
and followed byend
.All non-keyword arguments are converted to strings like
str
does and written to the stream, separated bysep
and followed byend
.If no objects are given,
overtype()
will just write"\\r"
.- Parameters
*objects – A list of strings or string-like objects to write to the terminal.
sep (
str
) – The separator between values. Default'␣'
.end (
str
) – The final value to print. Default''
.file (
Optional
[IO
]) – An object with awrite(string)
method. If not present orNone
,sys.stdout
will be used.flush (
bool
) – IfTrue
the stream is forcibly flushed after printing. DefaultFalse
.
typing
Various type annotation aids.
Type Hints
Type hint for objects that represent filesystem paths. |
|
Invariant |
|
Type hint for numbers. |
|
The type of methods of some built-in data types and base classes. |
|
The type of bound methods of some built-in data types and base classes. |
|
The type of methods of some built-in data types. |
|
The type of unbound class methods of some built-in data types. |
-
PathLike
Type hint for objects that represent filesystem paths.
See also
-
PathType
= TypeVar(PathType, str, Path, PathLike) Type:
TypeVar
Invariant
TypeVar
constrained tostr
,pathlib.Path
andos.PathLike
.Type variable for objects that represent filesystem paths.
New in version 2.2.0.
See also
-
AnyNumber
Type hint for numbers.
Changed in version 0.4.6: Moved from
domdf_python_tools.pagesizes
-
WrapperDescriptorType
The type of methods of some built-in data types and base classes, such as
object.__init__()
orobject.__lt__()
.New in version 0.8.0.
-
MethodWrapperType
The type of bound methods of some built-in data types and base classes. For example, it is the type of
object().__str__
.New in version 0.8.0.
-
MethodDescriptorType
The type of methods of some built-in data types, such as
str.join()
.New in version 0.8.0.
-
ClassMethodDescriptorType
The type of unbound class methods of some built-in data types, such as
dict.__dict__['fromkeys']
.New in version 0.8.0.
Protocols
|
|
|
|
|
|
Invariant |
|
|
|
|
|
|
|
|
|
|
-
protocol
JsonLibrary
[source] Bases:
Protocol
typing.Protocol
for libraries that implement the same API asjson
.Useful for annotating functions which take a JSON serialisation-deserialisation library as an argument.
Classes that implement this protocol must have the following methods / attributes:
-
static
dumps
(obj, *, skipkeys=..., ensure_ascii=..., check_circular=..., allow_nan=..., cls=..., indent=..., separators=..., default=..., sort_keys=..., **kwds)[source] Serialize
obj
to a JSON formattedstr
.
-
static
loads
(s, *, cls=..., object_hook=..., parse_float=..., parse_int=..., parse_constant=..., object_pairs_hook=..., **kwds)[source] Deserialize
s
to a Python object.
-
static
-
protocol
HasHead
[source] Bases:
Protocol
typing.Protocol
for classes that have ahead
method.This includes
pandas.DataFrame
andpandas.Series
.New in version 0.8.0.
This protocol is runtime checkable.
Classes that implement this protocol must have the following methods / attributes:
-
protocol
String
[source] Bases:
Protocol
Protocol
for classes that implement__str__
.Changed in version 0.8.0: Moved from
domdf_python_tools.stringlist
.This protocol is runtime checkable.
Classes that implement this protocol must have the following methods / attributes:
-
protocol
FrameOrSeries
New in version 1.0.0.
Classes that implement this protocol must have the following methods / attributes:
-
protocol
SupportsIndex
[source] Bases:
Protocol
typing.Protocol
for classes that support__index__
.New in version 2.0.0.
Classes that implement this protocol must have the following methods / attributes:
-
protocol
SupportsLessThan
[source] Bases:
Protocol
typing.Protocol
for classes that support__lt__
.New in version 3.0.0.
Classes that implement this protocol must have the following methods / attributes:
-
protocol
SupportsLessEqual
[source] Bases:
Protocol
typing.Protocol
for classes that support__le__
.New in version 3.0.0.
Classes that implement this protocol must have the following methods / attributes:
-
protocol
SupportsGreaterThan
[source] Bases:
Protocol
typing.Protocol
for classes that support__gt__
.New in version 3.0.0.
Classes that implement this protocol must have the following methods / attributes:
Utility Functions
-
check_membership
(obj, type_)[source] Check if the type of
obj
is one of the types in atyping.Union
,typing.Sequence
etc.- Parameters
obj (
Any
) – The object to check the type oftype_ (
Union
[Type
,object
]) – AType
that has members, such as atyping.List
,typing.Union
ortyping.Sequence
.
- Return type
utils
General utility functions.
Removed
tuple2str
andlist2string
. Usedomdf_python_tools.utils.list2str()
instead.Removed
as_text
andword_join
. Import fromdomdf_python_tools.words
instead.Removed
splitLen
. Usedomdf_python_tools.iterative.split_len()
instead.
Changed in version 2.0.0: chunks()
,
permutations()
,
split_len()
,
Len()
, and
double_chain()
moved to domdf_python_tools.iterative()
.
Changed in version 2.3.0: Removed domdf_python_tools.utils.deprecated()
.
Use the new deprecation-alias package instead.
Data:
The |
|
Object that provides an ellipsis string |
|
The current major python version. |
Functions:
|
Implementation of |
|
Convert indentation at the start of lines in |
|
Divide a string into two parts, about the given string. |
|
Like |
|
Adds single quotes ( |
|
Returns the head of the given object. |
|
Convert an iterable, such as a list, to a comma separated string. |
|
Returns the magnitude of the given value. |
|
Convert the positional args in |
|
Alias of |
|
Print the |
|
Print the type of an object. |
|
Context manager to redirect stdout and stderr to two |
|
Divide a string into two parts, splitting on the given regular expression. |
|
Replace nonprinting (control) characters in |
|
Print |
|
Convert a comma-separated string of integers into a tuple. |
|
|
|
Trim the precision of the given floating point value. |
|
Returns an ordered list of unique items from |
-
cmp
(x, y)[source] Implementation of
cmp
for Python 3.Compare the two objects x and y and return an integer according to the outcome.
The return value is negative if
x < y
, zero ifx == y
and strictly positive ifx > y
.- Return type
-
convert_indents
(text, tab_width=4, from_='\t', to=' ')[source] Convert indentation at the start of lines in
text
from tabs to spaces.
-
divide
(string, sep)[source] Divide a string into two parts, about the given string.
New in version 2.7.0.
-
double_repr_string
(string)[source] Like
repr(str)
, but tries to use double quotes instead.New in version 2.5.0.
-
enquote_value
(value)[source] Adds single quotes (
'
) to the given value, suitable for use in a templating system such as Jinja2.Floats
,integers
,booleans
,None
, and the strings'True'
,'False'
and'None'
are returned as-is.
-
etc
= ... Type:
_Etcetera
Object that provides an ellipsis string
New in version 0.8.0.
-
head
(obj, n=10)[source] Returns the head of the given object.
New in version 0.8.0.
- Parameters
See also
textwrap.shorten()
, which truncates a string to fit within a given number of characters.itertools.islice()
, which returns the firstn
elements from an iterator.
-
list2str
(the_list, sep=',')[source] Convert an iterable, such as a list, to a comma separated string.
-
magnitude
(x)[source] Returns the magnitude of the given value.
For negative numbers the absolute magnitude is returned.
For decimal numbers below
1
the magnitude will be negative.
New in version 2.0.0.
-
posargs2kwargs
(args, posarg_names, kwargs=None)[source] Convert the positional args in
args
to kwargs, based on the relative order ofargs
andposarg_names
.Important
Python 3.8’s Positional-Only Parameters (PEP 570) are not supported.
New in version 0.4.10.
- Parameters
args (
Iterable
[Any
]) – List of positional arguments provided to a function.posarg_names (
Union
[Iterable
[str
],Callable
]) – Either a list of positional argument names for the function, or the function object.kwargs (
Optional
[Dict
[str
,Any
]]) – Optional mapping of keyword argument names to values. The arguments will be added to this dictionary if provided. Default{}
.
- Return type
- Returns
Dictionary mapping argument names to values.
Changed in version 2.8.0: The “self” argument for bound methods is ignored. For unbound methods (which are just functions) the behaviour is unchanged.
-
printe
(*values, sep=' ', end='\n') Alias of
stderr_writer()
-
printr
(obj, *values, sep=' ', end='\n', file=None, flush=False)[source] Print the
repr()
of an object.If no objects are given,
printr()
will just writeend
.- Parameters
obj (
Any
)*values (
object
) – Additional values to print. These are printed verbatim.sep (
Optional
[str
]) – The separator between values. Default'␣'
.end (
Optional
[str
]) – The final value to print. Setting to''
will leave the insertion point at the end of the printed text. Default'\n'
.file (
Optional
[IO
]) – The file to write to. If not present orNone
,sys.stdout
will be used.flush (
bool
) – IfTrue
the stream is forcibly flushed after printing. DefaultFalse
.
-
printt
(obj, *values, sep=' ', end='\n', file=None, flush=False)[source] Print the type of an object.
If no objects are given,
printt()
will just writeend
.- Parameters
obj (
Any
)*values (
object
) – Additional values to print. These are printed verbatim.sep (
Optional
[str
]) – The separator between values. Default'␣'
.end (
Optional
[str
]) – The final value to print. Setting to''
will leave the insertion point at the end of the printed text. Default'\n'
.file (
Optional
[IO
]) – The file to write to. If not present orNone
,sys.stdout
will be used.flush (
bool
) – IfTrue
the stream is forcibly flushed after printing. DefaultFalse
.
-
redirect_output
(combine=False)[source] Context manager to redirect stdout and stderr to two
io.StringIO
objects.These are assigned (as a
tuple
) to the target theas
expression.Example:
with redirect_output() as (stdout, stderr): ...
New in version 2.6.0.
-
redivide
(string, pat)[source] Divide a string into two parts, splitting on the given regular expression.
New in version 2.7.0.
-
replace_nonprinting
(string, exclude=None)[source] Replace nonprinting (control) characters in
string
with^
andM-
notation.New in version 3.3.0.
- Parameters
- Return type
See also
C0 and C1 control codes on Wikipedia
-
stderr_writer
(*values, sep=' ', end='\n')[source] Print
*values
tosys.stderr
, separated bysep
and followed byend
.sys.stdout
is flushed before printing, andsys.stderr
is flushed afterwards.If no objects are given,
stderr_writer()
will just writeend
.- Parameters
Changed in version 3.0.0: The only permitted keyword arguments are
sep
andend
. Previous versions allowed other keywords arguments supported byprint()
but they had no effect.
-
str2tuple
(input_string, sep=',')[source] Convert a comma-separated string of integers into a tuple.
Important
The input string must represent a comma-separated series of integers.
-
strtobool
(val)[source] Convert a string representation of truth to
True
orFalse
.If val is an integer then its boolean representation is returned. If val is a boolean it is returned as-is.
True
values are'y'
,'yes'
,'t'
,'true'
,'on'
,'1'
, and1
.False
values are'n'
,'no'
,'f'
,'false'
,'off'
,'0'
, and0
.- Raises
ValueError
ifval
is anything else.- Return type
-
trim_precision
(value, precision=4)[source] Trim the precision of the given floating point value.
For example, if you have the value 170.10000000000002 but really only care about it being
≈ 179.1
:>>> trim_precision(170.10000000000002, 2) 170.1 >>> type(trim_precision(170.10000000000002, 2)) <class 'float'>
New in version 2.0.0.
-
unique_sorted
(elements, *, key=None, reverse=False)[source] Returns an ordered list of unique items from
elements
.New in version 3.0.0.
- Parameters
elements (
Iterable
)key (
Optional
[Callable
]) – A function of one argument used to extract a comparison key from each item when sorting. For example,key=str.lower
. The default value isNone
, which will compare the elements directly. DefaultNone
.reverse (
bool
) – IfTrue
the list elements are sorted as if each comparison were reversed. DefaultFalse
.
- Return type
- Overloads
unique_sorted
(elements:Iterable
[~SupportsLessThanT
], key:None
= …, reverse = … ) ->List
[~SupportsLessThanT
]unique_sorted
(elements:Iterable
[~_T
], key:Callable
[[~_T
],SupportsLessThan
], reverse = … ) ->List
[~_T
]
versions
NamedTuple-like class to represent a version number.
New in version 0.4.4.
Classes:
|
NamedTuple-like class to represent a version number. |
-
namedtuple
Version
(major=0, minor=0, patch=0)[source] -
NamedTuple-like class to represent a version number.
- Fields
Changed in version 1.4.0: Implemented the same interface as a
collections.namedtuple()
.-
__ge__
(other)[source] Returns whether this version is greater than or equal to the other version.
- Return type
-
__le__
(other)[source] Returns whether this version is less than or equal to the other version.
- Return type
-
_asdict
()[source] Return a new dict which maps field names to their corresponding values.
New in version 1.4.0.
-
_field_defaults
= {'major': 0, 'minor': 0, 'patch': 0} -
Dictionary mapping field names to default values.
New in version 1.4.0.
-
_fields
= ('major', 'minor', 'patch') -
Tuple of strings listing the field names.
Useful for introspection and for creating new named tuple types from existing named tuples.
New in version 1.4.0.
-
classmethod
_make
(iterable)[source] Class method that makes a new instance from an existing sequence or iterable.
New in version 1.4.0.
-
_replace
(**kwargs)[source] Return a new instance of the named tuple replacing specified fields with new values.
New in version 1.4.0.
- Parameters
kwargs
- Return type
~_V
-
classmethod
from_tuple
(version_tuple)[source] Create a
Version
from atuple
.- Parameters
version_tuple (
Tuple
[Union
[int
,str
], …]) – The version number.- Return type
~_V
- Returns
The created
Version
.
Changed in version 0.9.0: Tuples with more than three elements are truncated. Previously a
TypeError
was raised.
words
Functions for working with (English) words.
New in version 0.4.5.
Constants
Data:
The carriage return character ( |
|
The newline character ( |
|
A literal |
|
ASCII numbers. |
|
Lowercase Greek letters. |
|
Uppercase Greek letters. |
Fonts
Data:
Doublestruck |
|
Fraktur |
|
Monospace |
|
Bold and Italic Sans-Serif |
|
Bold Sans-Serif |
|
Italic Sans-Serif |
|
Normal Sans-Serif |
|
Script |
|
Bold and Italic Serif |
|
Bold Serif |
|
Italic Serif |
Classes:
Represents a Unicode pseudo-font. |
Functions:
|
Returns a dictionary mapping ASCII alphabetical characters and digits to the Unicode equivalents in a different pseudo-font. |
-
make_font
(uppers, lowers, digits=None, greek_uppers=None, greek_lowers=None)[source] Returns a dictionary mapping ASCII alphabetical characters and digits to the Unicode equivalents in a different pseudo-font.
New in version 0.7.0.
- Parameters
uppers (
Iterable
[str
]) – Iterable of uppercase letters (A-Z, 26 characters).lowers (
Iterable
[str
]) – Iterable of lowercase letters (a-z, 26 characters).digits (
Optional
[Iterable
[str
]]) – Optional iterable of digits (0-9). DefaultNone
.greek_uppers (
Optional
[Iterable
[str
]]) – Optional iterable of uppercase Greek letters (A-Ω, 25 characters). DefaultNone
.greek_lowers (
Optional
[Iterable
[str
]]) – Optional iterable of lowercase Greek letters (α-ϖ, 32 characters). DefaultNone
.
- Return type
-
class
Font
[source] -
Represents a Unicode pseudo-font.
Mapping of ASCII letters to their equivalents in the pseudo-font.
Individual characters can be converted using the
Font.get
method or thegetitem
syntax. Entire strings can be converted by calling theFont
object and passing the string as the first argument.Methods:
__call__
(text)Returns the given text in this font.
__getitem__
(char)Returns the given character in this font.
get
(char[, default])Returns the given character in this font.
-
__getitem__
(char)[source] Returns the given character in this font.
If the character is not found in this font the character is returned unchanged.
-
-
SERIF_BOLD_LETTERS
Bold Serif
Font
.This font includes numbers and Greek letters.
New in version 0.7.0.
-
SERIF_BOLD_ITALIC_LETTERS
Bold and Italic Serif
Font
.This font includes Greek letters.
New in version 0.7.0.
Functions
Functions:
|
Sorts a list of strings using a custom alphabet. |
|
Convert the given value to a string. |
|
Returns a random word, optionally only one whose length is between |
|
Returns the list of words, optionally only those whose length is between |
|
Join the given list of strings in a natural manner, with ‘and’ to join the last two elements. |
-
alpha_sort
(iterable, alphabet, reverse=False)[source] Sorts a list of strings using a custom alphabet.
New in version 0.7.0.
-
as_text
(value)[source] Convert the given value to a string.
None
is converted to''
.Changed in version 0.8.0: Moved from
domdf_python_tools.utils
.
-
get_words_list
(min_length=0, max_length=- 1)[source] Returns the list of words, optionally only those whose length is between
min_length
andmax_length
.New in version 0.4.5.
-
get_random_word
(min_length=0, max_length=- 1)[source] Returns a random word, optionally only one whose length is between
min_length
andmax_length
.New in version 0.4.5.
-
word_join
(iterable, use_repr=False, oxford=False, delimiter=',', connective='and')[source] Join the given list of strings in a natural manner, with ‘and’ to join the last two elements.
- Parameters
use_repr (
bool
) – Whether to join therepr
of each object. DefaultFalse
.oxford (
bool
) – Whether to use an oxford comma when joining the last two elements. DefaultFalse
. AlwaysFalse
if there are fewer than three elements.delimiter (
str
) – A single character to use between the words. Default','
.connective (
str
) – The connective to join the final two words with. Default'and'
.
- Return type
Changed in version 0.11.0: Added
delimiter
andconnective
arguments.
Classes
Classes:
|
Represents a word as its singular and plural. |
|
Represents a phrase which varies depending on a numerical count. |
-
class
Plural
(singular, plural)[source] Bases:
partial
Represents a word as its singular and plural.
New in version 2.0.0.
- Parameters
>>> cow = Plural("cow", "cows") >>> n = 1 >>> print(f"The farmer has {n} {cow(n)}.") The farmer has 1 cow. >>> n = 2 >>> print(f"The farmer has {n} {cow(n)}.") The farmer has 2 cows. >>> n = 3 >>> print(f"The farmer has {n} {cow(n)}.") The farmer has 3 cows.
Methods:
__call__
(n)Returns either the singular or plural form of the word depending on the value of
n
.__repr__
()Return a string representation of the
Plural
.
-
namedtuple
PluralPhrase
(template, words)[source] Bases:
NamedTuple
Represents a phrase which varies depending on a numerical count.
New in version 3.3.0.
- Fields
For example, consider the phase:
The proposed changes are to ...
The “phrase template” would be:
"The proposed {} {} to ..."
and the two words to insert are:
Plural("change", "changes") Plural("is", "are")
The phrase is constructed as follows:
>>> phrase = PluralPhrase( ... "The proposed {} {} to ...", ... (Plural("change", "changes"), Plural("is", "are")) ... ) >>> phrase(1) 'The proposed change is to ...' >>> phrase(2) 'The proposed changes are to ...'
The phrase template can use any valid syntax for
str.format()
, except for keyword arguments. The exception if the keywordn
, which is replaced with the count (e.g.2
) passed in when the phrase is constructed. For example:>>> phrase2 = PluralPhrase("The farmer has {n} {0}.", (Plural("cow", "cows"), )) >>> phrase2(2) 'The farmer has 2 cows.'
-
__repr__
() Return a string representation of the
PluralPhrase
.- Return type
pagesizes
List of common pagesizes and some tools for working with them.
This module defines a few common page sizes in points (1/72 inch).
classes
Classes representing pagesizes.
Classes:
|
Base class namedtuple representing a page size, in point. |
|
Represents a pagesize in point. |
|
Represents a pagesize in centimeters. |
|
Represents a pagesize in inches. |
|
Represents a pagesize in millimeters. |
|
Represents a pagesize in pica. |
|
Represents a pagesize in micrometers. |
-
namedtuple
BaseSize
(width, height)[source] Bases:
NamedTuple
Base class namedtuple representing a page size, in point.
-
namedtuple
PageSize
(width, height, unit=<Unit '1.000 pt': 1.000pt>)[source] Bases:
domdf_python_tools.pagesizes.classes.BaseSize
Represents a pagesize in point.
The pagesize can be converted to other units using the properties below.
-
namedtuple
Size_cm
(width, height)[source] Bases:
domdf_python_tools.pagesizes.classes.BaseSize
Represents a pagesize in centimeters.
-
namedtuple
Size_inch
(width, height)[source] Bases:
domdf_python_tools.pagesizes.classes.BaseSize
Represents a pagesize in inches.
-
namedtuple
Size_mm
(width, height)[source] Bases:
domdf_python_tools.pagesizes.classes.BaseSize
Represents a pagesize in millimeters.
-
namedtuple
Size_pica
(width, height)[source] Bases:
domdf_python_tools.pagesizes.classes.BaseSize
Represents a pagesize in pica.
-
namedtuple
Size_um
(width, height)[source] Bases:
domdf_python_tools.pagesizes.classes.BaseSize
Represents a pagesize in micrometers.
sizes
Common pagesizes in point/pt.
Each pagesize is an instance of domdf_python_tools.pagesizes.PageSize
.
The following sizes are available:
|
ISO 216 A0 Paper |
|
ISO 216 A1 Paper |
|
ISO 216 A10 Paper |
|
ISO 216 A2 Paper |
|
A2 Extra Paper |
|
ISO 216 A3 Paper |
|
A3 Extra Paper |
|
A3 Super Paper (different to (Super A3) |
|
ISO 216 A3 Paper |
|
A4 Extra Paper |
|
A4 Long Paper |
|
A4 Super Paper (different to (Super A4) |
|
ISO 216 A5 Paper |
|
A4 Extra Paper |
|
ISO 216 A6 Paper |
|
ISO 216 A7 Paper |
|
ISO 216 A8 Paper |
|
ISO 216 A0 Paper |
|
|
|
|
|
ISO 216 B0 Paper |
|
ISO 216 B1 Paper |
|
ISO 216 B10 Paper |
|
ISO 216 B2 Paper |
|
ISO 216 B3 Paper |
|
ISO 216 B4 Paper |
|
ISO 216 B5 Paper |
|
ISO 216 B6 Paper |
|
ISO 216 B7 Paper |
|
ISO 216 B8 Paper |
|
ISO 216 B9 Paper |
|
|
|
|
|
ISO 216 C0 Paper |
|
ISO 216 C1 Paper |
|
ISO 216 C10 Paper |
|
ISO 216 C2 Paper |
|
ISO 216 C3 Paper |
|
ISO 216 C4 Paper |
|
ISO 216 C5 Paper |
|
ISO 216 C6 Paper |
|
ISO 216 C7 Paper |
|
ISO 216 C8 Paper |
|
ISO 216 C9 Paper |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Emperor |
|
|
|
|
|
|
|
|
|
|
|
Government Legal |
|
Government Letter |
|
|
|
Half Letter |
|
|
|
SIM cards |
|
Most banking cards and ID cards |
|
French and other ID cards; Visas |
|
US government ID cards |
|
|
|
Junior Legal |
|
|
|
|
|
|
|
Ledger |
|
North American “Legal” Paper |
|
North American “Letter” Paper |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Quad Royal |
|
|
|
|
|
|
|
|
|
|
|
|
|
SO B5 Extra Paper |
|
Super A3 Paper (different to A3 Super) |
|
Super A3 Paper (different to A4 Super) |
|
units
Provides a variety of units for use with pagesizes.
Classes:
|
Represents a unit, such as a point. |
|
Inch. |
|
Centimetres. |
|
Millimetres. |
|
Pica. |
|
Point. |
|
Micrometres. |
Data:
|
Centimetre |
|
Inch |
|
Millimetre |
|
Pica |
|
Pica |
|
Point |
|
Micrometre |
-
class
Unit
(x=0, /)[source] Bases:
float
Represents a unit, such as a point.
Behaves much like a float (which it inherits from).
Addition
Units can be added to each other:
>>> (3*mm) + (7*mm) <Unit '10.000 mm': 28.346pt>
When adding different
Unit
objects, the result has the type of the former unit:>>> (2.54*cm) + inch <Unit '5.080 cm': 144.000pt> >>> inch + (2.54*cm) <Unit '2.000 inch': 144.000pt>
Unit
objects can also be added tofloat
andint
objects:>>> (3*cm) + 7 <Unit '10.000 cm': 283.465pt> >>> 7 + (3*cm) <Unit '10.000 cm': 283.465pt>
Subtraction
Subtraction works the same as addition:
>>> (17*mm) - (7*mm) <Unit '10.000 mm': 28.346pt> >>> (2.54*cm) - inch <Unit '0.000 cm': 0.000pt> >>> inch - (2.54*cm) <Unit '0.000 inch': 0.000pt> >>> (17*cm) - 7 <Unit '10.000 cm': 283.465pt> >>> 17 - (7*cm) <Unit '10.000 cm': 283.465pt>
Multiplication
Unit
objects can only be multipled byfloat
andint
objects:>>> (3*mm) * 3 <Unit '9.000 mm': 25.512pt> >>> 3 * (3*mm) <Unit '9.000 mm': 25.512pt> >>> 3.5 * (3*mm) <Unit '10.500 mm': 29.764pt>
Multiplication works either way round.
Multiplying by another
Unit
results in aNotImplementedError
:>>> inch * (7*cm) Traceback (most recent call last): NotImplementedError: Multiplying a unit by another unit is not allowed.
Division
Unit
s can only be divided byfloat
andint
objects:>>> (3*mm) / 3 <Unit '1.000 mm': 2.835pt> >>> (10*mm) / 2.5 <Unit '4.000 mm': 11.339pt>
Dividing by another unit results in a
NotImplementedError
:>>> inch / (7*cm) Traceback (most recent call last): NotImplementedError: Dividing a unit by another unit is not allowed.
Likewise, trying to divide a:class:float and
int
object by a unit results in aNotImplementedError
:>>> 3 / (3*mm) Traceback (most recent call last): NotImplementedError: Dividing by a unit is not allowed.
Powers
Powers (using
**
) are not officially supported.Modulo Division
Modulo division of a
Unit
by afloat
orint
object is allowed:>>> (3*mm) % 2.5 <Unit '0.500 mm': 1.417pt>
Dividing by a unit, or modulo division of two units, is not officially supported.
Methods:
__add__
(other)Return
self + value
.__call__
([value])Returns an instance of the
Unit
with the given value.__eq__
(other)Return
self == other
.__floordiv__
(other)Return
self // value
.__mod__
(other)Return
self % value
.__mul__
(other)Return
self * value
.__pow__
(power[, modulo])Return
pow(self, value, mod)
.__radd__
(other)Return
self + value
.__rdiv__
(other)Return
value / self
.__repr__
()Return a string representation of the
Unit
.__rmul__
(other)Return
self * value
.__rsub__
(other)Return
value - self
.__rtruediv__
(other)Return
value / self
.__str__
()Return
str(self)
.__sub__
(other)Return
value - self
.__truediv__
(other)Return
self / value
.as_pt
()Returns the unit in point.
from_pt
(value)Construct a
Unit
object from a value in point.Attributes:
-
__pow__
(power, modulo=None)[source] Return
pow(self, value, mod)
.
-
__rdiv__
(other) Return
value / self
.
-
utils
Tools for working with pagesizes.
Functions:
|
Convert |
|
Parse the given measurement. |
Overview
domdf_python_tools
uses tox to automate testing and packaging,
and pre-commit to maintain code quality.
Install pre-commit
with pip
and install the git hook:
python -m pip install pre-commit
pre-commit install
Coding style
formate is used for code formatting.
It can be run manually via pre-commit
:
pre-commit run formate -a
Or, to run the complete autoformatting suite:
pre-commit run -a
Automated tests
Tests are run with tox
and pytest
.
To run tests for a specific Python version, such as Python 3.6:
tox -e py36
To run tests for all Python versions, simply run:
tox
Build documentation locally
The documentation is powered by Sphinx. A local copy of the documentation can be built with tox
:
tox -e docs
Downloading source code
The domdf_python_tools
source code is available on GitHub,
and can be accessed from the following URL: https://github.com/domdfcoding/domdf_python_tools
If you have git
installed, you can clone the repository with the following command:
git clone https://github.com/domdfcoding/domdf_python_tools
Cloning into 'domdf_python_tools'...
remote: Enumerating objects: 47, done.
remote: Counting objects: 100% (47/47), done.
remote: Compressing objects: 100% (41/41), done.
remote: Total 173 (delta 16), reused 17 (delta 6), pack-reused 126
Receiving objects: 100% (173/173), 126.56 KiB | 678.00 KiB/s, done.
Resolving deltas: 100% (66/66), done.

Downloading a ‘zip’ file of the source code
Building from source
The recommended way to build domdf_python_tools
is to use tox:
tox -e build
The source and wheel distributions will be in the directory dist
.
If you wish, you may also use pep517.build or another PEP 517-compatible build tool.
License
domdf_python_tools
is licensed under the MIT License
A short and simple permissive license with conditions only requiring preservation of copyright and license notices. Licensed works, modifications, and larger works may be distributed under different terms and without source code.
Permissions | Conditions | Limitations |
---|---|---|
|
|
Copyright (c) 2019-2022 Dominic Davis-Foster
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
View the Function Index or browse the Source Code.