Skip to content

Commit 97768fd

Browse files
author
Hristo Valev
committed
update source
1 parent 7a63f92 commit 97768fd

File tree

6 files changed

+47
-117
lines changed

6 files changed

+47
-117
lines changed

markdownTable/__init__.py

Lines changed: 0 additions & 13 deletions
This file was deleted.

py_markdown_table/markdown_table.py

Lines changed: 23 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
1-
# -*- coding: utf-8 -*-
2-
"""Class used to generate formatted markdown tables. See class description"""
3-
import warnings
41
import math
52
from typing import Tuple, List, Dict
63
from py_markdown_table.utils import count_emojis, split_list_by_indices
74

85

9-
class markdown_table: # pylint: disable=C0103,R0902
6+
class markdown_table:
107
"""
118
A class used to generate padded tables in a markdown code block
129
@@ -133,6 +130,7 @@ def __init__(self, data):
133130
self.multiline_strategy = "rows"
134131
self.multiline_delimiter = " "
135132
self.quote = True
133+
self.validate = True
136134
self.__update_meta_params()
137135

138136
def set_params(
@@ -142,13 +140,14 @@ def set_params(
142140
padding_weight: str = "centerleft",
143141
padding_char: str = " ",
144142
newline_char: str = "\n",
145-
float_rounding: Tuple[int, type(None)] = None,
143+
float_rounding: Tuple[int, None] = None,
146144
emoji_spacing: str = None,
147-
multiline: Tuple[List[Dict], type(None)] = None,
145+
multiline: Tuple[List[Dict], None] = None,
148146
multiline_strategy: str = "rows",
149147
multiline_delimiter: str = " ",
150148
quote: bool = True,
151-
): # pylint: disable=R0913
149+
validate: bool = True,
150+
):
152151
"""Setter function for markdown table rendering parameters
153152
154153
Args:
@@ -178,7 +177,9 @@ def set_params(
178177
self.multiline_strategy = multiline_strategy
179178
self.multiline_delimiter = multiline_delimiter
180179
self.quote = quote
181-
self.__validate_parameters()
180+
self.validate = validate
181+
if validate:
182+
self.__validate_parameters()
182183
self.__update_meta_params()
183184
return self
184185

@@ -240,10 +241,7 @@ def __validate_parameters(self):
240241
f"multiline_strategy value of '{self.multiline_strategy}' is not valid. \
241242
Possible values are {*multiline_strategy_values,}."
242243
)
243-
if (
244-
not isinstance(self.multiline_delimiter, str)
245-
or len(str(self.multiline_delimiter)) != 1
246-
):
244+
if not isinstance(self.multiline_delimiter, str) or len(str(self.multiline_delimiter)) != 1:
247245
raise ValueError(
248246
f"multiline_delimiter value of '{self.multiline_delimiter}' is not valid. \
249247
Please use a single character string."
@@ -261,17 +259,13 @@ def __validate_data(self):
261259
for item in self.data:
262260
for key in keys:
263261
if key not in item:
264-
raise ValueError(
265-
"Dictionary keys are not uniform across data variable."
266-
)
262+
raise ValueError("Dictionary keys are not uniform across data variable.")
267263
if self.multiline:
268264
for row in self.data:
269265
for key, item in row.items():
270266
multiline_data = row[key].split(self.multiline_delimiter)
271267
multiline_max_width = max(multiline_data, key=len)
272-
if (self.var_padding[key]) < (
273-
len(multiline_max_width) + self.padding_width
274-
):
268+
if (self.var_padding[key]) < (len(multiline_max_width) + self.padding_width):
275269
raise ValueError(
276270
f"Contiguous string exists longer than the \
277271
allocated column width for column '{key}' \
@@ -343,7 +337,7 @@ def __get_row(self, item):
343337
def __get_normal_row(self, item):
344338
row = ""
345339
for key in self.data[0].keys():
346-
# preprend emoji pre-processing for cell values
340+
# prepend emoji pre-processing for cell values
347341
emoji = []
348342
if self.emoji_spacing == "mono":
349343
emoji = count_emojis(item[key])
@@ -352,13 +346,13 @@ def __get_normal_row(self, item):
352346
local_padding = self.var_padding[key] - len(emoji)
353347
margin = local_padding - len(str(item[key]))
354348
right = self.__get_margin(margin)
355-
row += "|" + str(item[key]).rjust(
356-
local_padding - right, self.padding_char
357-
).ljust(local_padding, self.padding_char)
349+
row += "|" + str(item[key]).rjust(local_padding - right, self.padding_char).ljust(
350+
local_padding, self.padding_char
351+
)
358352
row += "|"
359353
return row
360354

361-
def __get_multiline_row(self, item): # pylint: disable=R0912,R0914
355+
def __get_multiline_row(self, item):
362356
multiline_items = {}
363357
# process multiline rows column by column
364358
for key in self.data[0].keys():
@@ -373,9 +367,7 @@ def __get_multiline_row(self, item): # pylint: disable=R0912,R0914
373367
fully_split_cell.append(element)
374368
# if emojis are present, split by emoji into a list and concat
375369
else:
376-
emoji_indices = [
377-
emoji["index"] for emoji in emojis if "index" in emoji
378-
]
370+
emoji_indices = [emoji["index"] for emoji in emojis if "index" in emoji]
379371
emoji_split_element = split_list_by_indices(element, emoji_indices)
380372
fully_split_cell = fully_split_cell + emoji_split_element
381373

@@ -386,17 +378,9 @@ def __get_multiline_row(self, item): # pylint: disable=R0912,R0914
386378
while len(fully_split_cell) > 0:
387379
# check item length and adjust for presence of emoji
388380
# only check the first element since we are using a stack
389-
item_length = len(fully_split_cell[0]) + len(
390-
count_emojis(fully_split_cell[0])
391-
)
381+
item_length = len(fully_split_cell[0]) + len(count_emojis(fully_split_cell[0]))
392382

393-
if (
394-
item_length
395-
+ item_prev_length
396-
+ spacing_between_items
397-
+ self.padding_width
398-
<= self.var_padding[key]
399-
):
383+
if item_length + item_prev_length + spacing_between_items + self.padding_width <= self.var_padding[key]:
400384
# count just the items
401385
item_prev_length += item_length
402386
# add item to the current row
@@ -450,9 +434,9 @@ def get_header(self):
450434
for key in self.data[0].keys():
451435
margin = self.var_padding[key] - len(key)
452436
right = self.__get_margin(margin)
453-
header += "|" + key.rjust(
454-
self.var_padding[key] - right, self.padding_char
455-
).ljust(self.var_padding[key], self.padding_char)
437+
header += "|" + key.rjust(self.var_padding[key] - right, self.padding_char).ljust(
438+
self.var_padding[key], self.padding_char
439+
)
456440
header += "|" + self.newline_char
457441

458442
if self.row_sep == "always":
@@ -482,32 +466,3 @@ def get_markdown(self):
482466
if self.quote:
483467
return "```" + data + "```"
484468
return data
485-
486-
# backwards compatibility
487-
def getHeader(self): # pylint: disable=C0116,C0103
488-
warnings.warn(
489-
"the getHeader() function will be deprecated soon. Please use get_header() instead",
490-
DeprecationWarning,
491-
)
492-
return self.get_header()
493-
494-
def getBody(self): # pylint: disable=C0116,C0103
495-
warnings.warn(
496-
"the getBody() function will be deprecated soon. Please use get_body() instead",
497-
DeprecationWarning,
498-
)
499-
return self.get_body()
500-
501-
def getMarkdown(self): # pylint: disable=C0116,C0103
502-
warnings.warn(
503-
"the getMarkdown() function will be deprecated soon. Please use get_markdown() instead",
504-
DeprecationWarning,
505-
)
506-
return self.get_markdown()
507-
508-
def setParams(self, **keywords): # pylint: disable=C0116,C0103
509-
warnings.warn(
510-
"the setParams() function will be deprecated soon. Please use set_params() instead",
511-
DeprecationWarning,
512-
)
513-
return self.set_params(**keywords)

py_markdown_table/utils.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Util functions which may be used outside of the class for convenience"""
2+
23
from typing import List, Dict
34

45

@@ -39,19 +40,15 @@ def count_emojis(text: str) -> List[Dict]:
3940
and ord(text[i + 1]) >= 0xDC00
4041
and ord(text[i + 1]) <= 0xDFFF
4142
):
42-
code_point = (
43-
0x10000 + (ord(char) - 0xD800) * 0x400 + (ord(text[i + 1]) - 0xDC00)
44-
)
43+
code_point = 0x10000 + (ord(char) - 0xD800) * 0x400 + (ord(text[i + 1]) - 0xDC00)
4544
if any(start <= code_point <= end for start, end in emoji_ranges):
4645
emoji_info = {"index": i, "value": char + text[i + 1], "spacing": 2}
4746
emojis.append(emoji_info)
4847

4948
return emojis
5049

5150

52-
def find_longest_contiguous_strings(
53-
data: List[Dict], include_header: bool = False, delimiter: str = " "
54-
) -> Dict:
51+
def find_longest_contiguous_strings(data: List[Dict], include_header: bool = False, delimiter: str = " ") -> Dict:
5552
"""Finds the longest contiguous strings in a list of dicts.
5653
5754
Args:
@@ -68,7 +65,7 @@ def find_longest_contiguous_strings(
6865
longest_strings = {}
6966
if include_header:
7067
longest_strings = {key: len(key) for key in data[0].keys()}
71-
for dictionary in data: # pylint: disable=R1702
68+
for dictionary in data:
7269
for key, value in dictionary.items():
7370
if isinstance(value, str):
7471
max_length = 0

tests/tests.py

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,12 @@
5454
"date": "Thu 10.12",
5555
"seats": "18/18",
5656
},
57-
{"title": "Vrij Zwemmen", "time": "7:30-8:30", "date": "Fri 11.12", "seats": "😊🌍🎉"},
57+
{
58+
"title": "Vrij Zwemmen",
59+
"time": "7:30-8:30",
60+
"date": "Fri 11.12",
61+
"seats": "😊🌍🎉",
62+
},
5863
{
5964
"title": "Vrij Zwemmen",
6065
"time": "13:15-14:15",
@@ -137,21 +142,13 @@ def test_formatting_markdown():
137142

138143

139144
def test_formatting_markdown_noquote():
140-
mt = (
141-
markdown_table(formatting_data)
142-
.set_params(row_sep="markdown", quote=False)
143-
.get_markdown()
144-
)
145+
mt = markdown_table(formatting_data).set_params(row_sep="markdown", quote=False).get_markdown()
145146
res = "| title | time | date |seats|\n|------------|-----------|---------|-----|\n|Vrij Zwemmen|21:30-23:00|Wed 09.12|24/24|\n|Vrij Zwemmen|12:00-13:00|Thu 10.12|18/18|\n|Vrij Zwemmen| 7:30-8:30 |Fri 11.12|18/18|\n|Vrij Zwemmen|13:15-14:15|Sat 12.12|18/18|"
146147
assert mt == res
147148

148149

149150
def test_formatting_right():
150-
mt = (
151-
markdown_table(formatting_data)
152-
.set_params(row_sep="topbottom", padding_weight="right")
153-
.get_markdown()
154-
)
151+
mt = markdown_table(formatting_data).set_params(row_sep="topbottom", padding_weight="right").get_markdown()
155152
res = "```\n+----------------------------------------+\n|title |time |date |seats|\n|Vrij Zwemmen|21:30-23:00|Wed 09.12|24/24|\n|Vrij Zwemmen|12:00-13:00|Thu 10.12|18/18|\n|Vrij Zwemmen|7:30-8:30 |Fri 11.12|18/18|\n|Vrij Zwemmen|13:15-14:15|Sat 12.12|18/18|\n+----------------------------------------+```"
156153
assert mt == res
157154

@@ -237,11 +234,7 @@ def test_multirow_header_data():
237234

238235

239236
def test_emoji_data():
240-
mt = (
241-
markdown_table(emoji_data)
242-
.set_params(row_sep="topbottom", emoji_spacing="mono")
243-
.get_markdown()
244-
)
237+
mt = markdown_table(emoji_data).set_params(row_sep="topbottom", emoji_spacing="mono").get_markdown()
245238
res = "```\n+-----------------------------------------+\n| title | time | date | seats|\n|Vrij Zwemmen|21:30-23:00| 😊 | 24/24|\n|Vrij Zwemmen|12:00-13:00|Thu 10.12| 18/18|\n|Vrij Zwemmen| 7:30-8:30 |Fri 11.12|😊🌍🎉|\n|Vrij Zwemmen|13:15-14:15|Sat 12.12| 20/20|\n+-----------------------------------------+```"
246239
assert mt == res
247240

utils/benchmark.py

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,7 @@ def generate_dict_list(num_keys, num_dicts, values_length, include_whitespace=Fa
1212
for _ in range(num_dicts):
1313
dictionary = {}
1414
for key in keys:
15-
value = "".join(
16-
random.choice(string.ascii_letters + string.digits + " ")
17-
for _ in range(values_length)
18-
)
15+
value = "".join(random.choice(string.ascii_letters + string.digits + " ") for _ in range(values_length))
1916
dictionary[key] = value
2017
dict_list.append(dictionary)
2118
return dict_list
@@ -43,9 +40,7 @@ def generate_dict_list(num_keys, num_dicts, values_length, include_whitespace=Fa
4340
include_whitespace = include_whitespace_range[i]
4441

4542
# Generate the dictionary list for the current parameter combination
46-
dictionary_list = generate_dict_list(
47-
num_keys, num_dicts, values_length, include_whitespace
48-
)
43+
dictionary_list = generate_dict_list(num_keys, num_dicts, values_length, include_whitespace)
4944

5045
# Store the parameter combination and the generated dictionary list
5146
parameter_combinations.append(
@@ -81,9 +76,7 @@ def create_benchmark(columns, rows, cell_length, multiline, speed):
8176
# print(f"dictionary_list: {params['dictionary_list']}")
8277

8378
start_time = time.time() * 1000
84-
markdown_table(params["dictionary_list"]).set_params(
85-
padding_width=0, padding_weight="centerleft"
86-
).get_markdown()
79+
markdown_table(params["dictionary_list"]).set_params(padding_width=0, padding_weight="centerleft").get_markdown()
8780
end_time = time.time() * 1000
8881
elapsed_time = end_time - start_time
8982
print(f"Benchmark - Elapsed Time: {elapsed_time} milliseconds")

utils/gendesc.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# pylint: skip-file
2-
# flake8 noqa: E501
3-
from markdownTable import markdownTable
2+
from .. import markdown_table
43

54
# [monospaced fonts](https://en.wikipedia.org/wiki/Monospaced_font)
65
params = [
@@ -131,13 +130,19 @@
131130
"values": "",
132131
"description": "Wraps the generated markdown table in block quotes ```table```. Default is `True`.",
133132
},
133+
{
134+
"param": "validate",
135+
"type": "bool",
136+
"values": "",
137+
"description": "Whether to perform parameter validation when calling `set_params`. Default is `True`.",
138+
},
134139
]
135140

136141

137142
widths = {"param": 19, "type": 17, "values": 15, "description": 28}
138143

139144
print(
140-
markdownTable(params)
145+
markdown_table(params)
141146
.setParams(
142147
padding_char=" ",
143148
padding_weight="centerleft",

0 commit comments

Comments
 (0)