Skip to content

Commit 372b4a2

Browse files
authored
Verbosity (#1296)
* Verbosity - Implementing VerticaPy verbosity. [Only Part1 is implemented] * PART2 - multiple corrections * correction 3 * Correction 3 * PART 4 * PART5 - should be the last part of this change. * final correction
1 parent eacfc94 commit 372b4a2

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+360
-317
lines changed

verticapy/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@
3737
__url__: str = "https://github.com/vertica/verticapy/"
3838
__license__: str = "Apache License, Version 2.0"
3939
__version__: str = "1.0.5"
40-
__iteration__: int = 2
41-
__date__: str = "01102024"
40+
__iteration__: int = 1
41+
__date__: str = "02102024"
4242
__last_commit__: str = "c4fa73aaaf54051fb35b325a5dd77573ba9b3f4c"
4343
__long_version__: str = f"{__version__}-{__iteration__}{__date__}-{__last_commit__}"
4444
__codecov__: float = 0.84

verticapy/_config/config.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,10 @@ def set_option(key: str, value: Any = None) -> None:
379379
[bool]
380380
If set to ``True``, a loading bar is displayed
381381
when using iterative functions.
382+
- verbosity
383+
[int]
384+
API Verbosity, must be a value between 0 and 3.
385+
0 (silent) | 1 (warning) | 2 (info) | 3 (debug)
382386
383387
value: object, optional
384388
New value of the option.
@@ -758,3 +762,11 @@ def set_option(key: str, value: Any = None) -> None:
758762

759763
# Verbosity
760764
register_option(Option("print_info", True, "", bool_validator))
765+
register_option(
766+
Option(
767+
"verbosity",
768+
2,
769+
"",
770+
in_validator([0, 1, 2, 3]),
771+
)
772+
)

verticapy/_utils/_display.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
"""
1717
import html
1818
import shutil
19-
from typing import Optional
19+
from typing import Literal, Optional
2020

2121
import verticapy._config.config as conf
2222
from verticapy._typing import NoneType

verticapy/_utils/_parsers.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,15 @@
1717
import io
1818
import os
1919
from typing import List
20-
import warnings
2120

2221
import verticapy._config.config as conf
22+
from verticapy._utils._print import print_message
2323
from verticapy._utils._sql._format import list_strip
2424

2525
if conf.get_import_success("graphviz"):
2626
import graphviz
2727
from graphviz import Source
2828

29-
if conf.get_import_success("IPython"):
30-
from IPython.display import display
31-
3229
# CSV
3330

3431

@@ -104,7 +101,7 @@ def get_header_names(
104101
"to CSV while retaining its indexes.\nTip: Use "
105102
"index=False when exporting with pandas.DataFrame.to_csv."
106103
)
107-
warnings.warn(warning_message, Warning)
104+
print_message(warning_message, "warning")
108105
return list_strip(file_header)
109106

110107

@@ -329,8 +326,5 @@ def parse_explain_graphviz(rows: list[str], display_trees: bool = True) -> list:
329326
result += [row]
330327
if display_trees:
331328
for row in result:
332-
if isinstance(row, str) or not (conf.get_import_success("IPython")):
333-
print(row)
334-
else:
335-
display(row)
329+
print_message(row, "display")
336330
return result

verticapy/_utils/_print.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""
2+
Copyright (c) 2018-2024 Open Text or one of its
3+
affiliates. Licensed under the Apache License,
4+
Version 2.0 (the "License"); You may not use this
5+
file except in compliance with the License.
6+
7+
You may obtain a copy of the License at:
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in
11+
writing, software distributed under the License is
12+
distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
13+
OR CONDITIONS OF ANY KIND, either express or implied.
14+
See the License for the specific language governing
15+
permissions and limitations under the License.
16+
"""
17+
from typing import Literal
18+
import warnings
19+
20+
import verticapy._config.config as conf
21+
22+
if conf.get_import_success("IPython"):
23+
from IPython.display import display, HTML, Markdown
24+
25+
26+
def print_message(
27+
message: str, mtype: Literal["print", "warning", "display", "markdown"] = "print"
28+
) -> None:
29+
"""
30+
Prints the input message or warning.
31+
This function is used to manage the
32+
verbosity.
33+
"""
34+
mtype = mtype.lower().strip()
35+
if mtype == "warning" and conf.get_option("verbosity") >= 1:
36+
warnings.warn(message, Warning)
37+
elif (
38+
mtype == "print"
39+
and conf.get_option("print_info")
40+
and conf.get_option("verbosity") >= 2
41+
):
42+
print(message)
43+
elif (
44+
mtype in ("display", "markdown")
45+
and conf.get_option("print_info")
46+
and conf.get_option("verbosity") >= 2
47+
):
48+
if conf.get_import_success("IPython"):
49+
try:
50+
if mtype == "markdown":
51+
display(Markdown(message))
52+
else:
53+
display(HTML(message))
54+
except:
55+
display(message)
56+
else:
57+
print(message)

verticapy/_utils/_sql/_display.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,9 @@
1818
from typing import Optional
1919

2020
import verticapy._config.config as conf
21+
from verticapy._utils._print import print_message
2122
from verticapy._utils._sql._format import clean_query, indent_vpy_sql
2223

23-
if conf.get_import_success("IPython"):
24-
from IPython.display import HTML, display
25-
2624

2725
def print_query(query: str, title: Optional[str] = None) -> None:
2826
"""
@@ -64,13 +62,13 @@ def print_query(query: str, title: Optional[str] = None) -> None:
6462
query_print = clean_query(query)
6563
query_print = indent_vpy_sql(query)
6664
if conf.get_import_success("IPython"):
67-
display(HTML(f"<h4>{title}</h4>"))
65+
print_message(f"<h4>{title}</h4>", "display")
6866
query_print = query_print.replace("\n", " <br>").replace(" ", " &emsp; ")
69-
display(HTML(query_print))
67+
print_message(query_print, "display")
7068
else:
71-
print(f"$ {title} $\n")
72-
print(query_print)
73-
print("-" * int(screen_columns) + "\n")
69+
print_message(f"$ {title} $\n")
70+
print_message(query_print)
71+
print_message("-" * int(screen_columns) + "\n")
7472

7573

7674
def print_time(elapsed_time: float) -> None:
@@ -103,7 +101,9 @@ def print_time(elapsed_time: float) -> None:
103101
"""
104102
screen_columns = shutil.get_terminal_size().columns
105103
if conf.get_import_success("IPython"):
106-
display(HTML(f"<div><b>Execution: </b> {round(elapsed_time, 3)}s</div>"))
104+
print_message(
105+
f"<div><b>Execution: </b> {round(elapsed_time, 3)}s</div>", "display"
106+
)
107107
else:
108-
print(f"Execution: {round(elapsed_time, 3)}s")
109-
print("-" * int(screen_columns) + "\n")
108+
print_message(f"Execution: {round(elapsed_time, 3)}s")
109+
print_message("-" * int(screen_columns) + "\n")

verticapy/_utils/_sql/_format.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
permissions and limitations under the License.
1616
"""
1717
import re
18-
import warnings
1918
from typing import Any, Iterable, Literal, Optional
2019

2120
import numpy as np
@@ -24,13 +23,11 @@
2423

2524
import verticapy._config.config as conf
2625
from verticapy._utils._object import read_pd
26+
from verticapy._utils._print import print_message
2727
from verticapy._utils._sql._cast import to_dtype_category
2828
from verticapy._typing import NoneType, SQLColumns, SQLExpression
2929
from verticapy.errors import ParsingError
3030

31-
if conf.get_import_success("IPython"):
32-
from IPython.display import display, Markdown
33-
3431
"""
3532
SQL KEYWORDS
3633
"""
@@ -640,7 +637,6 @@ def format_query(
640637
construct others, simplifying the overall
641638
code.
642639
"""
643-
display_success = print_sql and conf.get_import_success("IPython")
644640
res = clean_query(query)
645641
html_res = res
646642

@@ -695,15 +691,13 @@ def format_query(
695691
.replace("\n", "<br>")
696692
.replace(" ", "&nbsp;&nbsp;&nbsp;&nbsp;")
697693
)
698-
if display_success:
699-
display(Markdown(html_res))
700694
if indent_sql:
701695
res = indent_vpy_sql(res)
702696
if print_sql:
703-
print(res)
697+
print_message(res, "markdown")
704698
if only_html:
705699
return html_res
706-
elif display_success:
700+
elif print_sql:
707701
return res, html_res
708702
return res, None
709703

@@ -1574,7 +1568,7 @@ def replace_vars_in_query(query: SQLExpression, locals_dict: dict) -> SQLExpress
15741568
warning_message = (
15751569
f"Failed to replace variables in the query.\nError: {e}"
15761570
)
1577-
warnings.warn(warning_message, Warning)
1571+
print_message(warning_message, "warning")
15781572
fail = True
15791573
if not fail:
15801574
object_type = None

verticapy/_utils/_sql/_sys.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,9 @@ def _executeSQL(
172172
query = clean_query(query)
173173

174174
cursor = current_cursor()
175-
if conf.get_option("sql_on") and print_time_sql:
175+
if (
176+
conf.get_option("sql_on") or (conf.get_option("verbosity") == 3)
177+
) and print_time_sql:
176178
print_query(query, title)
177179
start_time = time.time()
178180
if data:
@@ -183,7 +185,9 @@ def _executeSQL(
183185
else:
184186
cursor.execute(query)
185187
elapsed_time = time.time() - start_time
186-
if conf.get_option("time_on") and print_time_sql:
188+
if (
189+
conf.get_option("time_on") or (conf.get_option("verbosity") == 3)
190+
) and print_time_sql:
187191
print_time(elapsed_time)
188192
if method == "fetchrow":
189193
return cursor.fetchone()

verticapy/connection/connect.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@
2121
from vertica_python.vertica.cursor import Cursor
2222
from vertica_python.vertica.connection import Connection
2323

24-
import verticapy._config.config as conf
24+
from verticapy._utils._print import print_message
25+
2526
from verticapy.connection.errors import ConnectionError, OAuthTokenRefreshError
2627
from verticapy.connection.global_connection import (
2728
get_global_connection,
@@ -142,10 +143,9 @@ def connect(section: str, dsn: Optional[str] = None) -> None:
142143
gb_conn.set_connection(
143144
vertica_connection(section, dsn, config=None), section, dsn
144145
)
145-
if conf.get_option("print_info"):
146-
print("Connected Successfully!")
146+
print_message("Connected Successfully!")
147147
except OAuthTokenRefreshError as error:
148-
print(
148+
print_message(
149149
"Access Denied: Your authentication credentials are incorrect or have expired. Please retry"
150150
)
151151
new_connection(
@@ -155,13 +155,12 @@ def connect(section: str, dsn: Optional[str] = None) -> None:
155155
gb_conn.set_connection(
156156
vertica_connection(section, dsn, config=None), section, dsn
157157
)
158-
if conf.get_option("print_info"):
159-
print("Connected Successfully!")
158+
print_message("Connected Successfully!")
160159
except OAuthTokenRefreshError as error:
161-
print("Error persists:")
160+
print_message("Error persists:")
162161
raise error
163162
except ConnectionError as error:
164-
print(
163+
print_message(
165164
"A connection error occured. Common reasons may be an invalid host, port, or, if requiring "
166165
"OAuth and token refresh, this may be due to an incorrect or malformed token url."
167166
)

verticapy/connection/oauth_manager.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,11 @@
1818
from __future__ import print_function, division, absolute_import, annotations
1919

2020
import requests
21-
import warnings
2221

23-
from urllib3.poolmanager import PoolManager
2422
from requests.adapters import HTTPAdapter
23+
from urllib3.poolmanager import PoolManager
2524

26-
25+
from verticapy._utils._print import print_message
2726
from verticapy.connection.errors import (
2827
OAuthTokenRefreshError,
2928
OAuthConfigurationError,
@@ -66,7 +65,7 @@ def set_config(self, configs) -> None:
6665
for k, v in configs.items():
6766
if k not in valid_keys:
6867
invalid_key = f"Unrecognized OAuth config property: {k}"
69-
warnings.warn(invalid_key)
68+
print_message(invalid_key, "warning")
7069
continue
7170
if v is None or v == "": # ignore empty value
7271
continue

0 commit comments

Comments
 (0)