Skip to content

Commit 5121271

Browse files
committed
Moving functions to more appropriate locations.
1 parent decf346 commit 5121271

File tree

8 files changed

+150
-87
lines changed

8 files changed

+150
-87
lines changed

doc-source/api/words.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,7 @@ Functions for working with (English) words.
5151

5252
.. autodata:: domdf_python_tools.words.DOUBLESTRUCK_LETTERS
5353
:annotation:
54+
55+
.. autofunction:: domdf_python_tools.words.as_text
56+
57+
.. autofunction:: domdf_python_tools.words.word_join

domdf_python_tools/paths.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
# paths.py
44
"""
55
Functions for paths and files.
6+
7+
.. versionchanged:: 0.8.0
8+
9+
``relpath2`` is deprecated and will be removed in 1.0.0.
10+
Use :func:`domdf_python_tools.paths.relpath` instead.
611
"""
712
#
813
# Copyright © 2018-2020 Dominic Davis-Foster <[email protected]>
@@ -43,6 +48,7 @@
4348
from typing import IO, Any, Callable, Iterable, List, Optional
4449

4550
# this package
51+
from domdf_python_tools.stringlist import StringList
4652
from domdf_python_tools.typing import JsonLibrary, PathLike
4753

4854
__all__ = [
@@ -253,24 +259,16 @@ def clean_writer(string: str, fp: IO) -> None:
253259
Write string to ``fp`` without trailing spaces.
254260
255261
:param string:
256-
:type string: str
257262
:param fp:
258263
"""
259264

260-
buffer = []
261-
262-
for line in string.split('\n'):
263-
buffer.append(line.rstrip())
264-
265-
while buffer[-1:] == ['']:
266-
buffer = buffer[:-1]
265+
buffer = StringList(string)
266+
buffer.blankline(ensure_single=True)
267267

268-
if not buffer:
269-
fp.write('\n')
268+
if len(buffer) == 1 and buffer.count_blanklines() == 1:
269+
buffer.blankline()
270270

271-
for line in buffer:
272-
fp.write(line)
273-
fp.write('\n')
271+
fp.write(str(buffer))
274272

275273

276274
def make_executable(filename: PathLike) -> None:

domdf_python_tools/stringlist.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,8 @@ def copy(self) -> "StringList":
181181
def count_blanklines(self) -> int:
182182
"""
183183
Returns a count of the blank lines in the :class:`~domdf_python_tools.stringlist.StringList`.
184+
185+
.. versionadded:: 0.7.1
184186
"""
185187

186188
return self.count('')

domdf_python_tools/utils.py

Lines changed: 29 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@
44
# utils.py
55
"""
66
General utility functions
7+
8+
.. versionchanged:: 0.8.0
9+
10+
``tuple2str`` and ``list2string`` are deprecated and will be removed in 1.0.0.
11+
Use :func:`domdf_python_tools.utils.list2str` instead.
712
"""
813
#
914
# Copyright © 2018-2020 Dominic Davis-Foster <[email protected]>
@@ -48,16 +53,18 @@
4853
import itertools
4954
import sys
5055
from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Sequence, Tuple, Union
56+
from domdf_python_tools import __version__
57+
import deprecation # type: ignore
58+
import domdf_python_tools.words
59+
5160

5261
__all__ = [
5362
"pyversion",
5463
"SPACE_PLACEHOLDER",
55-
"as_text",
5664
"check_dependencies",
5765
"chunks",
5866
"cmp",
5967
"list2str",
60-
"tuple2str",
6168
"permutations",
6269
"printr",
6370
"printt",
@@ -71,7 +78,6 @@
7178
"Len",
7279
"double_chain",
7380
"posargs2kwargs",
74-
"word_join",
7581
"convert_indents",
7682
]
7783

@@ -82,26 +88,12 @@
8288
SPACE_PLACEHOLDER = '␣'
8389

8490

85-
def as_text(value: Any) -> str:
86-
"""
87-
Convert the given value to a string. ``None`` is converted to ``''``.
88-
89-
:param value: Value to convert to a string
90-
"""
91-
92-
if value is None:
93-
return ''
94-
95-
return str(value)
96-
97-
9891
def check_dependencies(dependencies: Iterable[str], prt: bool = True) -> List[str]:
9992
"""
10093
Check whether one or more dependencies are available to be imported.
10194
10295
:param dependencies: The list of dependencies to check the availability of.
10396
:param prt: Whether the status should be printed to the terminal. Default :py:obj:`True`.
104-
:type prt: bool, optional
10597
10698
:return: A list of any missing modules
10799
"""
@@ -134,7 +126,6 @@ def chunks(l: Sequence[Any], n: int) -> Generator[Any, None, None]:
134126
135127
:param l: The objects to yield chunks from
136128
:param n: The size of the chunks
137-
:type n: int
138129
"""
139130

140131
for i in range(0, len(l), n):
@@ -166,6 +157,7 @@ def list2str(the_list: Iterable[Any], sep: str = ',') -> str:
166157
return sep.join([str(x) for x in the_list])
167158

168159

160+
# Will be removed in 1.0.0
169161
tuple2str = list2string = list2str
170162

171163

@@ -225,9 +217,7 @@ def split_len(string: str, n: int) -> List[str]:
225217
Split a string every ``n`` characters.
226218
227219
:param string: The string to split
228-
:type string: str
229220
:param n: The number of characters to split after
230-
:type n: int
231221
232222
:return: The split string
233223
"""
@@ -249,9 +239,7 @@ def str2tuple(input_string: str, sep: str = ',') -> Tuple[int, ...]:
249239
.. TODO:: Allow custom types, not just ``int`` (making ``int`` the default)
250240
251241
:param input_string: The string to be converted into a tuple
252-
:type input_string: str
253242
:param sep: The separator in the string. Default `,`
254-
:type sep: str
255243
"""
256244

257245
return tuple(int(x) for x in input_string.split(sep))
@@ -284,7 +272,7 @@ def strtobool(val: Union[str, bool]) -> bool:
284272

285273
def enquote_value(value: Any) -> Union[str, bool, float]:
286274
"""
287-
Adds quotes (``'``) to the given value, suitable for use in a templating system such as Jinja2.
275+
Adds single quotes (``'``) to the given value, suitable for use in a templating system such as Jinja2.
288276
289277
:class:`Floats <float>`, :class:`integers <int>`, :class:`booleans <bool>`, :py:obj:`None`,
290278
and the strings ``'True'``, ``'False'`` and ``'None'`` are returned as-is.
@@ -342,7 +330,7 @@ def double_chain(iterable: Iterable[Iterable]):
342330
[1, 2, 3, 4, 5, 6, 7, 8]
343331
344332
345-
:param iterable: The iterable to
333+
:param iterable: The iterable to chain.
346334
:return:
347335
348336
.. versionadded:: 0.4.7
@@ -381,41 +369,13 @@ def posargs2kwargs(
381369
return kwargs
382370

383371

384-
def word_join(iterable: Iterable[str], use_repr: bool = False, oxford: bool = False) -> str:
385-
"""
386-
Join the given list of strings in a natural manner, with 'and' to join the last two elements.
387-
388-
:param iterable:
389-
:param use_repr: Whether to join the ``repr`` of each object.
390-
:param oxford: Whether to use an oxford comma when joining the last two elements.
391-
Always :py:obj:`False` if there are less than three elements.
392-
"""
393-
394-
if use_repr:
395-
words = [repr(w) for w in iterable]
396-
else:
397-
words = list(iterable)
398-
399-
if len(words) == 0:
400-
return ''
401-
elif len(words) == 1:
402-
return words[0]
403-
elif len(words) == 2:
404-
return " and ".join(words)
405-
else:
406-
if oxford:
407-
return ", ".join(words[:-1]) + f", and {words[-1]}"
408-
else:
409-
return ", ".join(words[:-1]) + f" and {words[-1]}"
410-
411-
412372
def convert_indents(text: str, tab_width: int = 4, from_: str = "\t", to: str = " ") -> str:
413-
"""
373+
r"""
414374
Convert indentation at the start of lines in ``text`` from tabs to spaces.
415375
416376
:param text: The text to convert indents in.
417377
:param tab_width: The number of spaces per tab.
418-
:param from_: The indent to convert from.
378+
:param from\_: The indent to convert from.
419379
:param to: The indent to convert to.
420380
"""
421381

@@ -425,10 +385,24 @@ def convert_indents(text: str, tab_width: int = 4, from_: str = "\t", to: str =
425385

426386
for line in text.splitlines():
427387
indent_count = 0
388+
428389
while line.startswith(from_):
429390
indent_count += 1
430-
print(indent_count)
431391
line = line[from_size:]
392+
432393
output.append(f"{tab * indent_count}{line}")
433394

434395
return "\n".join(output)
396+
397+
398+
as_text = deprecation.deprecated(
399+
deprecated_in="0.8.0", removed_in="1.0.0",
400+
current_version=__version__,
401+
details="Import from 'domdf_python_tools.words' instead.",
402+
)(domdf_python_tools.words.as_text)
403+
404+
word_join = deprecation.deprecated(
405+
deprecated_in="0.8.0", removed_in="1.0.0",
406+
current_version=__version__,
407+
details="Import from 'domdf_python_tools.words' instead.",
408+
)(domdf_python_tools.words.word_join)

domdf_python_tools/words.py

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,8 @@
4646

4747
# this package
4848
import domdf_python_tools
49-
from domdf_python_tools.paths import PathPlus
5049

5150
__all__ = [
52-
"ascii_digits",
5351
"greek_uppercase",
5452
"greek_lowercase",
5553
"get_words_list",
@@ -68,6 +66,8 @@
6866
"MONOSPACE_LETTERS",
6967
"DOUBLESTRUCK_LETTERS",
7068
"alpha_sort",
69+
"as_text",
70+
"word_join",
7171
]
7272

7373
ascii_digits = "0123456789"
@@ -107,6 +107,8 @@ def get_words_list(min_length: int = 0, max_length: int = -1) -> List[str]:
107107
.. versionadded:: 0.4.5
108108
"""
109109

110+
from domdf_python_tools.paths import PathPlus
111+
110112
with importlib_resources.path(domdf_python_tools, "google-10000-english-no-swears.txt") as words_file_:
111113
words_file = PathPlus(words_file_)
112114

@@ -478,3 +480,48 @@ def make_font(
478480
479481
.. versionadded:: 0.7.0
480482
"""
483+
484+
485+
def as_text(value: Any) -> str:
486+
"""
487+
Convert the given value to a string. ``None`` is converted to ``''``.
488+
489+
:param value: The value to convert to a string.
490+
491+
.. versionchanged:: 0.8.0
492+
493+
Moved from :mod:`domdf_python_tools.utils`.
494+
"""
495+
496+
if value is None:
497+
return ''
498+
499+
return str(value)
500+
501+
502+
def word_join(iterable: Iterable[str], use_repr: bool = False, oxford: bool = False) -> str:
503+
"""
504+
Join the given list of strings in a natural manner, with 'and' to join the last two elements.
505+
506+
:param iterable:
507+
:param use_repr: Whether to join the ``repr`` of each object.
508+
:param oxford: Whether to use an oxford comma when joining the last two elements.
509+
Always :py:obj:`False` if there are fewer than three elements.
510+
"""
511+
512+
if use_repr:
513+
words = [repr(w) for w in iterable]
514+
else:
515+
words = list(iterable)
516+
517+
if len(words) == 0:
518+
return ''
519+
elif len(words) == 1:
520+
return words[0]
521+
elif len(words) == 2:
522+
return " and ".join(words)
523+
else:
524+
if oxford:
525+
return ", ".join(words[:-1]) + f", and {words[-1]}"
526+
else:
527+
return ", ".join(words[:-1]) + f" and {words[-1]}"

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ colorama>=0.4.3
22
importlib_resources>=3.0.0
33
pydash>=4.7.4
44
typing_extensions>=3.7.4.3
5+
deprecation>=2.1.0

tests/test_utils.py

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -26,23 +26,6 @@ def test_pyversion():
2626
assert isinstance(utils.pyversion, int)
2727

2828

29-
@pytest.mark.parametrize(
30-
"value, expects",
31-
[
32-
(12345, "12345"),
33-
(123.45, "123.45"),
34-
([123.45], "[123.45]"),
35-
({123.45}, "{123.45}"),
36-
((123.45, ), "(123.45,)"),
37-
(None, ''),
38-
(pathlib.Path('.'), '.'),
39-
(decimal.Decimal("1234"), "1234"),
40-
]
41-
)
42-
def test_as_text(value, expects):
43-
assert utils.as_text(value) == expects
44-
45-
4629
def test_check_dependencies(capsys):
4730
deps = ["pytest", "domdf_python_tools", "madeup_module"]
4831

0 commit comments

Comments
 (0)