Skip to content

Commit bd2873f

Browse files
authored
Merge pull request #129 from timlnx/context-note
misc doc fixups
2 parents 185d48f + de20588 commit bd2873f

6 files changed

Lines changed: 66 additions & 50 deletions

File tree

.github/workflows/python.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ jobs:
3535
3636
- name: Pre-Tests code smell validation
3737
run: |
38-
pycodestyle -v --ignore=E501,E722 bitmath/__init__.py tests/
38+
pycodestyle -v --ignore=E501 bitmath/__init__.py tests/
3939
flake8 --select=F bitmath/__init__.py tests/
4040
4141
- name: Run Unit Tests

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ ci-pycodestyle:
207207
@echo "#############################################"
208208
@echo "# Running PEP8 Compliance Tests in virtualenv"
209209
@echo "#############################################"
210-
. $(NAME)env3/bin/activate && pycodestyle -v --ignore=E501,E722 bitmath/__init__.py tests/*.py
210+
. $(NAME)env3/bin/activate && pycodestyle -v --ignore=E501 bitmath/__init__.py tests/*.py
211211

212212
ci-flake8:
213213
@echo ""

bitmath/__init__.py

Lines changed: 3 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# SPDX-License-Identifier: MIT
33
# The MIT License (MIT)
44
#
5-
# Copyright © 2014-2016 Tim Case <timbielawa@gmail.com>
5+
# Copyright © 2014-2026 Tim Case <bitmath@lnx.cx>
66
# See GitHub Contributors Graph for more information
77
#
88
# Permission is hereby granted, free of charge, to any person
@@ -24,7 +24,7 @@
2424
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2525
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2626
# SOFTWARE.
27-
# pylint: disable=bad-continuation,missing-docstring,invalid-name,line-too-long
27+
# pylint: disable=line-too-long
2828

2929
"""Reference material:
3030
The bitmath homepage is located at:
@@ -785,17 +785,6 @@ def __ge__(self, other):
785785

786786
# Reference: https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types
787787

788-
"""These methods are called to implement the binary arithmetic
789-
operations (+, -, *, //, %, divmod(), pow(), **, <<, >>, &, ^, |). For
790-
instance, to evaluate the expression x + y, where x is an instance of
791-
a class that has an __add__() method, x.__add__(y) is called. The
792-
__divmod__() method should be the equivalent to using __floordiv__()
793-
and __mod__(); it should not be related to __truediv__() (described
794-
below). Note that __pow__() should be defined to accept an optional
795-
third argument if the ternary version of the built-in pow() function
796-
is to be supported.object.__complex__(self)
797-
"""
798-
799788
def __add__(self, other):
800789
"""Supported operations with result types:
801790
@@ -895,20 +884,6 @@ def __divmod__(self, other):
895884

896885
##################################################################
897886

898-
"""These methods are called to implement the binary arithmetic
899-
operations (+, -, *, /, %, divmod(), pow(), **, <<, >>, &, ^, |) with
900-
reflected (swapped) operands. These functions are only called if the
901-
left operand does not support the corresponding operation and the
902-
operands are of different types. [2] For instance, to evaluate the
903-
expression x - y, where y is an instance of a class that has an
904-
__rsub__() method, y.__rsub__(x) is called if x.__sub__(y) returns
905-
NotImplemented.
906-
907-
These are the add/sub/mul/div methods for syntax where a number type
908-
is given for the LTYPE and a bitmath object is given for the
909-
RTYPE. E.g., 3 * MiB(3), or 10 / GB(42)
910-
"""
911-
912887
def __radd__(self, other):
913888
# Special case: 0 + bm = bm (identity element, enables built-in sum())
914889
if other == 0:
@@ -1663,10 +1638,7 @@ def parse_string(s: str | numbers.Number, system: int = NIST, strict: bool = Tru
16631638
val = float(val)
16641639
except ValueError:
16651640
raise
1666-
try:
1667-
return unit_class(val)
1668-
except: # pragma: no cover
1669-
raise ValueError(f"Can't parse string {s} into a bitmath object")
1641+
return unit_class(val)
16701642

16711643
else:
16721644
# strict=False path (formerly parse_string_unsafe)

docsite/source/contributing.rst

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,13 @@ Two static analysis checks run on every pull request as part of the
4343
GitHub Actions CI workflow, and locally via ``make ci``:
4444

4545
* ``pycodestyle`` — checks code style, with **E501** (line too long)
46-
and **E722** (bare ``except``) ignored.
46+
ignored.
4747
* ``flake8 --select=F`` — runs pyflakes error checks only (undefined
4848
names, unused imports, etc.). Style checks are disabled.
4949

50-
A PR cannot be merged until both pass. Run ``make ci`` locally to
51-
check before submitting.
50+
A PR cannot be merged until both pass. If you want to save time you
51+
can run ``make ci`` locally to check before submitting and waiting on
52+
the GitHub runners to report back.
5253

5354

5455
.. _contributing_commit_messages:
@@ -102,7 +103,7 @@ This means the minimum supported version tracks the oldest Python still
102103
included in a supported EPEL target:
103104

104105
* **RHEL 10 / EPEL 10** — Python 3.12
105-
* **RHEL 9 / EPEL 9** — Python 3.9, 3.11
106+
* **RHEL 9 / EPEL 9** — Python 3.9, 3.10, 3.11
106107

107108
The CI matrix tests all versions in this range. When a RHEL major
108109
release reaches end-of-life and is dropped from EPEL, the corresponding

docsite/source/module.rst

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -714,16 +714,10 @@ This section describes all of the `context managers
714714
<https://docs.python.org/3/reference/datamodel.html#context-managers>`_
715715
provided by the bitmath class.
716716

717-
.. warning::
718-
719-
It is a known limitation that the bitmath context managers are
720-
**not thread-safe**. You may get unexpected results or errors using
721-
these in a threaded environment.
722-
723-
The suggested workaround is to apply formatting to each object
724-
instance directly. See the instance :ref:`format
725-
<instances_format>` method docs for additional reference.
717+
.. note::
726718

719+
Context manager settings are thread safe. Concurrent contexts in
720+
different threads do not interfere with each other.
727721

728722
.. note::
729723

@@ -777,8 +771,6 @@ bitmath.format()
777771
unit.
778772

779773

780-
.. note:: The ``bestprefix`` parameter is not yet implemented!
781-
782774
Let's look at an example of toggling pluralization on and
783775
off. First we'll look over a demonstration script (below), and then
784776
we'll review the output.
@@ -865,13 +857,13 @@ bitmath.format()
865857
866858
>>> import bitmath
867859
>>> print("Some instances: %s, %s" % (bitmath.KiB(1 / 3.0), bitmath.Bit(512)))
868-
Some instances: 0.333333333333 KiB, 512.0 b
860+
Some instances: 0.3333333333333333 KiB, 512.0 b
869861
>>> with bitmath.format("{value:e}-{unit}"):
870862
... print("Some instances: %s, %s" % (bitmath.KiB(1 / 3.0), bitmath.Bit(512)))
871863
...
872864
Some instances: 3.333333e-01-KiB, 5.120000e+02-b
873865
>>> print("Some instances: %s, %s" % (bitmath.KiB(1 / 3.0), bitmath.Bit(512)))
874-
Some instances: 0.333333333333 KiB, 512.0 b
866+
Some instances: 0.3333333333333333 KiB, 512.0 b
875867
876868
877869
.. versionadded:: 1.0.8

docsite/source/real_life_examples.rst

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,57 @@ The result on line **4** tells tells us that we could fit **256**
8585
average-quality songs on our iPod.
8686

8787

88+
Using Real Device Capacity
89+
==========================
90+
91+
Rather than hard-coding a device size, we can query the actual free
92+
space on any mounted filesystem with :func:`bitmath.query_capacity`
93+
and feed that directly into the same calculation.
94+
95+
:func:`bitmath.query_capacity` returns a :class:`Capacity` named
96+
tuple with ``total``, ``used``, and ``free`` fields. By default
97+
(``bestprefix=True``) each field is already normalized to a
98+
human-readable prefix (e.g. ``GiB``). Pass ``bestprefix=False`` to
99+
get raw :class:`bitmath.Byte` instances instead. It requires no
100+
elevated privileges and works cross-platform.
101+
102+
.. code-block:: python
103+
104+
>>> import bitmath
105+
>>> cap = bitmath.query_capacity("/")
106+
>>> print(cap.free)
107+
93.08 GiB
108+
109+
Now we can ask: *how many 4.7 GB DVD images fit in that free space?*
110+
111+
.. code-block:: python
112+
113+
>>> dvd = bitmath.GB(4.7)
114+
>>> count, remainder = divmod(cap.free, dvd)
115+
>>> print(int(count), "DVDs,", remainder.best_prefix(), "left over")
116+
19 DVDs, 3.262 GiB left over
117+
118+
Floor division (``//``) and modulo (``%``) work the same way if you
119+
only need one value:
120+
121+
.. code-block:: python
122+
123+
>>> print(int(cap.free // dvd), "DVDs fit")
124+
19 DVDs fit
125+
>>> print((cap.free % dvd).best_prefix(), "remaining")
126+
3.262 GiB remaining
127+
128+
.. seealso::
129+
130+
:ref:`Capacity Math <capacity_math>`
131+
Details on floor division, modulo, and ``divmod`` for bitmath
132+
objects.
133+
134+
:func:`bitmath.query_capacity`
135+
Full reference for the ``Capacity`` named tuple and
136+
cross-platform behaviour.
137+
138+
88139
Printing Human-Readable File Sizes in Python
89140
********************************************
90141

0 commit comments

Comments
 (0)