UltraPython 1.8.5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ultrapython-1.8.5/.github/workflows/publish.yml +20 -0
- ultrapython-1.8.5/.gitignore +218 -0
- ultrapython-1.8.5/LICENSE +21 -0
- ultrapython-1.8.5/PKG-INFO +355 -0
- ultrapython-1.8.5/README.md +319 -0
- ultrapython-1.8.5/pyproject.toml +24 -0
- ultrapython-1.8.5/src/ultrapython/__init__.py +1 -0
- ultrapython-1.8.5/src/ultrapython/ultrapython.py +757 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
build-and-publish:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
permissions:
|
|
11
|
+
id-token: write
|
|
12
|
+
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v4
|
|
15
|
+
- uses: actions/setup-python@v5
|
|
16
|
+
with:
|
|
17
|
+
python-version: "3.12"
|
|
18
|
+
- run: pip install build
|
|
19
|
+
- run: python -m build
|
|
20
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
# Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
# uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
# poetry.lock
|
|
109
|
+
# poetry.toml
|
|
110
|
+
|
|
111
|
+
# pdm
|
|
112
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
113
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
114
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
115
|
+
# pdm.lock
|
|
116
|
+
# pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# pixi
|
|
121
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
122
|
+
# pixi.lock
|
|
123
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
124
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
125
|
+
.pixi
|
|
126
|
+
|
|
127
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
128
|
+
__pypackages__/
|
|
129
|
+
|
|
130
|
+
# Celery stuff
|
|
131
|
+
celerybeat-schedule
|
|
132
|
+
celerybeat.pid
|
|
133
|
+
|
|
134
|
+
# Redis
|
|
135
|
+
*.rdb
|
|
136
|
+
*.aof
|
|
137
|
+
*.pid
|
|
138
|
+
|
|
139
|
+
# RabbitMQ
|
|
140
|
+
mnesia/
|
|
141
|
+
rabbitmq/
|
|
142
|
+
rabbitmq-data/
|
|
143
|
+
|
|
144
|
+
# ActiveMQ
|
|
145
|
+
activemq-data/
|
|
146
|
+
|
|
147
|
+
# SageMath parsed files
|
|
148
|
+
*.sage.py
|
|
149
|
+
|
|
150
|
+
# Environments
|
|
151
|
+
.env
|
|
152
|
+
.envrc
|
|
153
|
+
.venv
|
|
154
|
+
env/
|
|
155
|
+
venv/
|
|
156
|
+
ENV/
|
|
157
|
+
env.bak/
|
|
158
|
+
venv.bak/
|
|
159
|
+
|
|
160
|
+
# Spyder project settings
|
|
161
|
+
.spyderproject
|
|
162
|
+
.spyproject
|
|
163
|
+
|
|
164
|
+
# Rope project settings
|
|
165
|
+
.ropeproject
|
|
166
|
+
|
|
167
|
+
# mkdocs documentation
|
|
168
|
+
/site
|
|
169
|
+
|
|
170
|
+
# mypy
|
|
171
|
+
.mypy_cache/
|
|
172
|
+
.dmypy.json
|
|
173
|
+
dmypy.json
|
|
174
|
+
|
|
175
|
+
# Pyre type checker
|
|
176
|
+
.pyre/
|
|
177
|
+
|
|
178
|
+
# pytype static type analyzer
|
|
179
|
+
.pytype/
|
|
180
|
+
|
|
181
|
+
# Cython debug symbols
|
|
182
|
+
cython_debug/
|
|
183
|
+
|
|
184
|
+
# PyCharm
|
|
185
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
186
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
187
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
188
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
189
|
+
# .idea/
|
|
190
|
+
|
|
191
|
+
# Abstra
|
|
192
|
+
# Abstra is an AI-powered process automation framework.
|
|
193
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
194
|
+
# Learn more at https://abstra.io/docs
|
|
195
|
+
.abstra/
|
|
196
|
+
|
|
197
|
+
# Visual Studio Code
|
|
198
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
199
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
200
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
201
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
202
|
+
# .vscode/
|
|
203
|
+
# Temporary file for partial code execution
|
|
204
|
+
tempCodeRunnerFile.py
|
|
205
|
+
|
|
206
|
+
# Ruff stuff:
|
|
207
|
+
.ruff_cache/
|
|
208
|
+
|
|
209
|
+
# PyPI configuration file
|
|
210
|
+
.pypirc
|
|
211
|
+
|
|
212
|
+
# Marimo
|
|
213
|
+
marimo/_static/
|
|
214
|
+
marimo/_lsp/
|
|
215
|
+
__marimo__/
|
|
216
|
+
|
|
217
|
+
# Streamlit
|
|
218
|
+
.streamlit/secrets.toml
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Abdyrahym Begenjov
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: UltraPython
|
|
3
|
+
Version: 1.8.5
|
|
4
|
+
Summary: UltraPython: Utilities of Files, Databases, and Math
|
|
5
|
+
Project-URL: Homepage, https://github.com
|
|
6
|
+
Author: Abdyrahym Begenjov
|
|
7
|
+
License: MIT License
|
|
8
|
+
|
|
9
|
+
Copyright (c) 2026 Abdyrahym Begenjov
|
|
10
|
+
|
|
11
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
12
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
13
|
+
in the Software without restriction, including without limitation the rights
|
|
14
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
15
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
16
|
+
furnished to do so, subject to the following conditions:
|
|
17
|
+
|
|
18
|
+
The above copyright notice and this permission notice shall be included in all
|
|
19
|
+
copies or substantial portions of the Software.
|
|
20
|
+
|
|
21
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
22
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
23
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
24
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
25
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
26
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
27
|
+
SOFTWARE.
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Requires-Python: >=3.10
|
|
30
|
+
Requires-Dist: numpy
|
|
31
|
+
Requires-Dist: openpyxl
|
|
32
|
+
Requires-Dist: pandas
|
|
33
|
+
Requires-Dist: pyarrow
|
|
34
|
+
Requires-Dist: sqlalchemy
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# ultrapython-module
|
|
38
|
+
## English
|
|
39
|
+
## UltraPython: Utilities of Files, Databases, and Math 🐍
|
|
40
|
+
UltraPython is a simple and helpful Python library. It helps you work with different files, connect to databases, and do math operations without writing long code. It is great for automating your daily programming tasks.
|
|
41
|
+
> **Note:** This library requires Python 3.10+ because it uses the modern match-case feature.
|
|
42
|
+
|
|
43
|
+
## Key Features
|
|
44
|
+
* **All-in-One File Tools:** Read, write, and append `.txt`, `.json`, `.pickle`, `.csv`, `.parquet`, and `.xlsx` (Excel) files easily.
|
|
45
|
+
* **Smart Excel Styles:** Automatically makes Excel columns wide enough for your data and adds nice colors and fonts.
|
|
46
|
+
* **Simple SQL Database Tools:** Connect to PostgreSQL, MySQL, or SQLite, and move data between files and databases quickly.
|
|
47
|
+
* **Better Math:** Easy functions for math rounding, finding roots, and solving equations.
|
|
48
|
+
|
|
49
|
+
## API Reference & Function Capabilities
|
|
50
|
+
|
|
51
|
+
### `pyread(filename, *, encoding='utf-8', as_list=False, **kwargs)`
|
|
52
|
+
* **Description:** Reads data from a file. It automatically knows the format by looking at the file extension.
|
|
53
|
+
* **Capabilities:**
|
|
54
|
+
* Automatically handles 6 formats: `.txt`, `.json`, `.pickle`, `.csv`, `.parquet`, and `.xlsx`.
|
|
55
|
+
* If you read a `.txt` file with `as_list=True`, it automatically splits the text into a clean list of lines.
|
|
56
|
+
* If you read an Excel file with only one sheet, it automatically extracts it as a single DataFrame instead of a dictionary.
|
|
57
|
+
* Passes extra options (`**kwargs`) directly to internal readers like `pandas.read_csv` or `pandas.read_excel`.
|
|
58
|
+
|
|
59
|
+
### `pyrewrite(filename, value, *, encoding='utf-8', sheet_name=None, ...)`
|
|
60
|
+
* **Description:** Clears the target file and writes completely new data into it.
|
|
61
|
+
* **Capabilities:**
|
|
62
|
+
* Supports writing strings and lists to `.txt`, dictionaries to `.json`/`.pickle`, and dataframes to `.csv`/`.parquet`/`.xlsx`.
|
|
63
|
+
* For Excel (`.xlsx`), it automatically designs your table: adds bold headers, custom colors, fonts, and clean thin borders.
|
|
64
|
+
* Automatically auto-fits the Excel column widths based on the longest text in each column.
|
|
65
|
+
* Automatically sets cell data formats in Excel (detects categories, integers, floats, dates, and times).
|
|
66
|
+
|
|
67
|
+
### `pyadd(filename, value, *, encoding='utf-8', sheet_name=None, **kwargs)`
|
|
68
|
+
* **Description:** Adds new data to the end of an existing file without deleting the old content.
|
|
69
|
+
* **Capabilities:**
|
|
70
|
+
* For `.txt` files, it appends new text lines directly to the end.
|
|
71
|
+
* For `.json` and `.pickle`, it reads the old data first, merges it safely with the new data using `pyupdate`, and overwrites the file.
|
|
72
|
+
* For `.csv` and `.xlsx` dataframes, it automatically separates and filters arguments for reading and writing so your code does not crash.
|
|
73
|
+
|
|
74
|
+
### `pyupdate(d1, d2)`
|
|
75
|
+
* **Description:** A helper function that merges two dictionaries recursively.
|
|
76
|
+
* **Capabilities:**
|
|
77
|
+
* If the same key exists in both dictionaries, it combines their values into a list or extends them instead of overwriting.
|
|
78
|
+
* Safely merges Python lists, tuples, sets, frozensets, and deques.
|
|
79
|
+
* Supports deep nested dictionary updates at any level.
|
|
80
|
+
|
|
81
|
+
### `make_sqlengine(db_name, db_user=None, db_password=None, db_host='localhost', db_port=5432, db_type='postgres')`
|
|
82
|
+
* **Description:** Creates a connection object (engine) for your database using SQLAlchemy.
|
|
83
|
+
* **Capabilities:**
|
|
84
|
+
* Supports 3 popular database systems: PostgreSQL/Postgres, MySQL, and SQLite.
|
|
85
|
+
* Automatically builds the correct connection string URL so you do not have to memorize syntax.
|
|
86
|
+
|
|
87
|
+
### `sqlread(query, db_name, **kwargs)`
|
|
88
|
+
* **Description:** Runs an SQL query and returns the result table as a `pandas.DataFrame`.
|
|
89
|
+
* **Capabilities:**
|
|
90
|
+
* Automatically opens and closes the database connection for you.
|
|
91
|
+
* Accepts all configuration parameters from `make_sqlengine`.
|
|
92
|
+
|
|
93
|
+
### `sqlrewrite(table_name, new_value, db_name, ..., chunksize=50000, **kwargs)`
|
|
94
|
+
* **Description:** Replaces an old table in the database with a new DataFrame.
|
|
95
|
+
* **Capabilities:**
|
|
96
|
+
* Uploads data in small parts (chunks) to protect your computer's RAM.
|
|
97
|
+
* Uses the fast multi insert method to send data to the database quickly.
|
|
98
|
+
|
|
99
|
+
### `sqladd(table_name, new_value, db_name, ..., chunksize=50000, **kwargs)`
|
|
100
|
+
* **Description:** Appends new rows from a DataFrame to the end of an existing database table.
|
|
101
|
+
* **Capabilities:**
|
|
102
|
+
* Never deletes old database data; it only appends.
|
|
103
|
+
* Uses the same fast chunk-by-chunk processing system as `sqlrewrite`.
|
|
104
|
+
|
|
105
|
+
### `transform_from_sql(filepath, query, db_name, **kwargs)`
|
|
106
|
+
* **Description:** Takes data from a database query and saves it directly into a file.
|
|
107
|
+
* **Capabilities:**
|
|
108
|
+
* Exports database tables to `.csv`, `.parquet`, or styled `.xlsx` with one line of code.
|
|
109
|
+
* Automatically filters valid writing parameters depending on the chosen file extension.
|
|
110
|
+
|
|
111
|
+
### `transform_to_sql(filepath, table_name, db_name, **kwargs)`
|
|
112
|
+
* **Description:** Reads data from a file and uploads it directly into a database table.
|
|
113
|
+
* **Capabilities:**
|
|
114
|
+
* Connects `pyread` and `sqlrewrite` together automatically.
|
|
115
|
+
* Detects and links file reading parameters with database writing rules.
|
|
116
|
+
|
|
117
|
+
### `onelist(lst)`
|
|
118
|
+
* **Description:** Takes a complex nested collection and flattens it into one simple, single list.
|
|
119
|
+
* **Capabilities:**
|
|
120
|
+
* Uses recursion to unpack structures of any depth.
|
|
121
|
+
* Unpacks list, tuple, set, frozenset, and deque all at once.
|
|
122
|
+
|
|
123
|
+
### `super_round(value, num=0)`
|
|
124
|
+
* **Description:** Rounds numbers using standard symmetric school math rules (where 0.5 always rounds up away from zero).
|
|
125
|
+
* **Capabilities:**
|
|
126
|
+
* Bypasses Python's built-in "banker's rounding" (round-to-even) for predictable math results.
|
|
127
|
+
* Uses optimized string slices and list reversals for reliable parsing.
|
|
128
|
+
|
|
129
|
+
### `root(number, base=2, precision=2)`
|
|
130
|
+
* **Description:** Finds the root of a number with a specific degree and rounds the result.
|
|
131
|
+
* **Capabilities:**
|
|
132
|
+
* Supports square roots, cube roots, and higher degrees.
|
|
133
|
+
* Automatically blocks impossible operations (like even roots of negative numbers or degrees less than 2).
|
|
134
|
+
* Cleans the output using `super_round`.
|
|
135
|
+
|
|
136
|
+
### `quadratic_equation(a, b=0, c=0)`
|
|
137
|
+
* **Description:** Solves standard quadratic equations (ax² + bx + c = 0).
|
|
138
|
+
* **Capabilities:**
|
|
139
|
+
* Safely processes linear cases if a = 0 or b = 0.
|
|
140
|
+
* Returns `None` if there are no real roots, one number if there is one root, or a tuple `(x1, x2)` if there are two roots.
|
|
141
|
+
|
|
142
|
+
### `take_month(value)`
|
|
143
|
+
* **Description:** Converts months from any format to a numeric value.
|
|
144
|
+
* **Capabilities:** Supports Russian and English.
|
|
145
|
+
|
|
146
|
+
### `take_weekday(value, start_zero, start_sunday)`
|
|
147
|
+
* **Description:** Converts weekdays from any format to a numeric value.
|
|
148
|
+
* **Capabilities:**
|
|
149
|
+
* Supports Russian and English.
|
|
150
|
+
* Automatically handles different types of weekday indexing.
|
|
151
|
+
|
|
152
|
+
### `distributor(s)`
|
|
153
|
+
* **Description:** A finite state machine that creates values from string elements in a list.
|
|
154
|
+
* **Capabilities:** Distributes values by arrow and numeric type.
|
|
155
|
+
|
|
156
|
+
### `work_timezone1(value, to_tz, from_tz)`
|
|
157
|
+
* **Description:** Converts from one time zone to another and assigns the destination time zone to the result.
|
|
158
|
+
* **Capabilities:** Supports many different time zones.
|
|
159
|
+
|
|
160
|
+
### `work_timezone2(value, keyword, to_tz, from_tz)`
|
|
161
|
+
* **Description:** Converts a datetime object to a string.
|
|
162
|
+
* **Capabilities:** The result depends on the parameters and the specified datetime object type.
|
|
163
|
+
|
|
164
|
+
### `relative_datetime(value, keyword, *, current_date='now', current_time='now', current_datetime='now', from_tz=none, to_tz=none)`
|
|
165
|
+
* **Description:** Converts from relative string dates and times to a DateTime object.
|
|
166
|
+
* * **Capabilities:**
|
|
167
|
+
* Supports Russian and English.
|
|
168
|
+
* Many operations with relative dates and times.
|
|
169
|
+
|
|
170
|
+
### `make_date(value, *, order='ymd', current_date='now', century=21, start_sunday=False, start_zero=False)`
|
|
171
|
+
* **Description:** Converts various forms of string dates to a datetime object.
|
|
172
|
+
* **Capabilities:**
|
|
173
|
+
* Supports Russian and English.
|
|
174
|
+
* Supports the current date and any date specified for calculations with other dates.
|
|
175
|
+
* Includes many features, including the internal functions relative_datetime, take_month, and take_weekday.
|
|
176
|
+
* Handling short year entries using the century parameter.
|
|
177
|
+
* Arrangement of year, month, day, day of the week, and week numbering.
|
|
178
|
+
|
|
179
|
+
### `make_time(value, *, order='HMS', current_time='now', from_tz=None, to_tz=None)`
|
|
180
|
+
* **Description:** Converts various forms of string times to a time object.
|
|
181
|
+
* **Capabilities:**
|
|
182
|
+
* Supports Russian and English.
|
|
183
|
+
* Supports the current time and specifies any time for calculations with other times.
|
|
184
|
+
* Includes many features, including the internal functions relative_time and distributor.
|
|
185
|
+
* Smart validation of time unit ranges.
|
|
186
|
+
* Working with time zones and automatic determination of the local time zone.
|
|
187
|
+
|
|
188
|
+
### `make_datetime(value, *, order_date='yMD', order_time='hms', century=21, isFirstTime=false, start_sunday=false, start_zero=false, current_datetime='now', from_tz=none, to_tz=none)`
|
|
189
|
+
* **Description:** Converts from different forms String dates + time to the DateTime object.
|
|
190
|
+
* **Capabilities:**
|
|
191
|
+
* Supports Russian and English.
|
|
192
|
+
* Support the current date and time and prescribing any dates and times for calculation with other dates and times.
|
|
193
|
+
* Includes a lot of functionality, including internal functions Relative_DateTime, make_date, make_time, work_timezone1 and work_timezone2.
|
|
194
|
+
|
|
195
|
+
## Русский
|
|
196
|
+
## UltraPython: утилиты файлов, баз данных и математики 🐍
|
|
197
|
+
|
|
198
|
+
UltraPython — это простая и полезная библиотека для Python. Она помогает работать с различными файлами, подключаться к базам данных и выполнять математические операции без написания длинного кода. Отлично подходит для автоматизации ваших повседневных задач программирования.
|
|
199
|
+
|
|
200
|
+
> **Примечание:** Для работы библиотеки требуется Python 3.10+, так как в ней используется современный механизм сопоставления шаблонов (match-case).
|
|
201
|
+
|
|
202
|
+
## Основные возможности
|
|
203
|
+
|
|
204
|
+
* **Универсальные файлы:** Легкое чтение, запись и добавление данных в `.txt`, `.json`, `.pickle`, `.csv`, `.parquet` и `.xlsx` (Excel).
|
|
205
|
+
* **Красивый Excel:** Автоматически подбирает ширину колонок и добавляет красивые шрифты и цвета в таблицы.
|
|
206
|
+
* **Простая работа с SQL:** Подключение к PostgreSQL, MySQL или SQLite и быстрый перенос данных между файлами и базой.
|
|
207
|
+
* **Полезная математика:** Удобные функции для округления чисел, поиска корней и решения уравнений.
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
## Описание функций и их возможностей
|
|
212
|
+
|
|
213
|
+
### `pyread(filename, *, encoding='utf-8', as_list=False, **kwargs)`
|
|
214
|
+
* **Описание:** Читает данные из файла. Автоматически определяет нужный формат по его расширению.
|
|
215
|
+
* **Возможности:**
|
|
216
|
+
* Работает с 6 популярными форматами: `.txt`, `.json`, `.pickle`, `.csv`, `.parquet` и `.xlsx`.
|
|
217
|
+
* Если читать `.txt` с параметром `as_list=True`, функция автоматически разобьет текст на список строк.
|
|
218
|
+
* При чтении Excel с одним листом автоматически извлекает его как чистый DataFrame, а не словарь.
|
|
219
|
+
* Пробрасывает дополнительные параметры (`**kwargs`) во внутренние методы `pandas`.
|
|
220
|
+
|
|
221
|
+
### `pyrewrite(filename, value, *, encoding='utf-8', sheet_name=None, ...)`
|
|
222
|
+
* **Описание:** Полностью удаляет старое содержимое файла и записывает в него новые данные.
|
|
223
|
+
* **Возможности:**
|
|
224
|
+
* Поддерживает запись строк/списков в `.txt`, словарей в `.json`/`.pickle` и таблиц в `.csv`/`.parquet`/`.xlsx`.
|
|
225
|
+
* При сохранении в Excel автоматически наводит красоту: делает жирные заголовки, рамки ячеек, настраивает цвета и шрифты.
|
|
226
|
+
* Автоматически растягивает ширину колонок Excel под самый длинный текст в столбце.
|
|
227
|
+
* Сама выставляет форматы данных для ячеек Excel (текст, целые числа, дроби, даты и время).
|
|
228
|
+
|
|
229
|
+
### `pyadd(filename, value, *, encoding='utf-8', sheet_name=None, **kwargs)`
|
|
230
|
+
* **Описание:** Добавляет новые данные в конец существующего файла без удаления старой информации.
|
|
231
|
+
* **Возможности:**
|
|
232
|
+
* В `.txt` файлах просто дописывает новые строки в самый конец.
|
|
233
|
+
* В `.json` и `.pickle` сначала считывает старые данные, безопасно объединяет их с новыми через `pyupdate` и перезаписывает файл.
|
|
234
|
+
* Для таблиц `.csv` и `.xlsx` автоматически разделяет и фильтрует аргументы чтения и записи, предотвращая ошибки.
|
|
235
|
+
|
|
236
|
+
### `pyupdate(d1, d2)`
|
|
237
|
+
* **Описание:** Помощник для рекурсивного (глубокого) объединения двух словарей.
|
|
238
|
+
* **Возможности:**
|
|
239
|
+
* Если ключи в словарях совпадают, функция не перезаписывает данные, а объединяет их элементы в один общий список.
|
|
240
|
+
* Безопасно работает со структурами `list`, `tuple`, `set`, `frozenset` и `deque`.
|
|
241
|
+
* Поддерживает слияние вложенных словарей на любой глубине.
|
|
242
|
+
|
|
243
|
+
### `make_sqlengine(db_name, db_user=None, db_password=None, db_host='localhost', db_port=5432, db_type='postgres')`
|
|
244
|
+
* **Описание:** Создает объект подключения (engine) к базе данных через SQLAlchemy.
|
|
245
|
+
* **Возможности:**
|
|
246
|
+
* Поддерживает 3 популярные СУБД: PostgreSQL/Postgres, MySQL и SQLite.
|
|
247
|
+
* Сама собирает правильную строку подключения, избавляя вас от необходимости писать её вручную.
|
|
248
|
+
|
|
249
|
+
### `sqlread(query, db_name, **kwargs)`
|
|
250
|
+
* **Описание:** Выполняет SQL-запрос и возвращает полученную таблицу в виде `pandas.DataFrame`.
|
|
251
|
+
* **Возможности:**
|
|
252
|
+
* Сама открывает и закрывает соединение с базой данных «под капотом».
|
|
253
|
+
* Принимает все те же настройки подключения, что и `make_sqlengine`.
|
|
254
|
+
|
|
255
|
+
### `sqlrewrite(table_name, new_value, db_name, ..., chunksize=50000, **kwargs)`
|
|
256
|
+
* **Описание:** Полностью удаляет старую таблицу в базе данных и записывает на её место новый DataFrame.
|
|
257
|
+
* **Возможности:**
|
|
258
|
+
* Загружает данные небольшими частями (chunks), что защищает оперативную память компьютера от перегрузки.
|
|
259
|
+
* Использует быстрый метод `multi` для ускоренной пакетной вставки строк в БД.
|
|
260
|
+
|
|
261
|
+
### `sqladd(table_name, new_value, db_name, ..., chunksize=50000, **kwargs)`
|
|
262
|
+
* **Описание:** Добавляет новые строки из DataFrame в конец существующей таблицы в базе данных.
|
|
263
|
+
* **Возможности:**
|
|
264
|
+
* Никогда не удаляет старые данные в БД, только дописывает новые.
|
|
265
|
+
* Использует ту же производительную систему разбивки на чанки, что и `sqlrewrite`.
|
|
266
|
+
|
|
267
|
+
### `transform_from_sql(filepath, query, db_name, **kwargs)`
|
|
268
|
+
* **Описание:** Берет данные из базы данных по SQL-запросу и сохраняет их напрямую в файл.
|
|
269
|
+
* **Возможности:**
|
|
270
|
+
* Экспортирует таблицы из БД в файлы `.csv`, `.parquet` или стилизованный `.xlsx` одной строчкой кода.
|
|
271
|
+
* Сама подбирает корректные параметры записи в зависимости от выбранного расширения файла.
|
|
272
|
+
|
|
273
|
+
### `transform_to_sql(filepath, table_name, db_name, **kwargs)`
|
|
274
|
+
* **Описание:** Читает данные из файла и сразу загружает их в таблицу базы данных.
|
|
275
|
+
* **Возможности:**
|
|
276
|
+
* Автоматически объединяет логику функций `pyread` и `sqlrewrite`.
|
|
277
|
+
* Самостоятельно связывает параметры чтения файлов с правилами записи в SQL.
|
|
278
|
+
|
|
279
|
+
### `onelist(lst)`
|
|
280
|
+
* **Описание:** Принимает сложную вложенную коллекцию и превращает её в один плоский простой список.
|
|
281
|
+
* **Возможности:**
|
|
282
|
+
* Использует рекурсию, позволяя разбирать структуры любой глубины вложенности.
|
|
283
|
+
* Успешно извлекает элементы из `list`, `tuple`, `set`, `frozenset` и `deque`.
|
|
284
|
+
|
|
285
|
+
### `super_round(value, num=0)`
|
|
286
|
+
* **Описание:** Округляет числа по стандартным школьным правилам математики (где 0.5 всегда округляется в большую сторону от нуля).
|
|
287
|
+
* **Возможности:**
|
|
288
|
+
* Позволяет обойти встроенное в Python «банковское округление» (к ближайшему четному) для получения предсказуемых результатов.
|
|
289
|
+
* Использует строковые срезы и развороты списков для точного разбора долей числа.
|
|
290
|
+
|
|
291
|
+
### `root(number, base=2, precision=2)`
|
|
292
|
+
* **Описание:** Находит корень числа любой степени и округляет итоговый результат.
|
|
293
|
+
* **Возможности:**
|
|
294
|
+
* Считает квадратные, кубические и любые корни высших степеней.
|
|
295
|
+
* Автоматически блокирует невозможные операции (например, извлечение четного корня из отрицательного числа или степень корня меньше 2).
|
|
296
|
+
* Финально обрабатывает результат через `super_round`.
|
|
297
|
+
|
|
298
|
+
### `quadratic_equation(a, b=0, c=0)`
|
|
299
|
+
* **Описание:** Решает стандартные квадратные уравнения (ax² + bx + c = 0).
|
|
300
|
+
* **Возможности:**
|
|
301
|
+
* Безопасно обрабатывает линейные случаи, если коэффициенты `a` или `b` равны нулю.
|
|
302
|
+
* Возвращает `None`, если вещественных корней нет, одно число при единственном корне или кортеж `(x1, x2)`, если корней два.
|
|
303
|
+
|
|
304
|
+
### `take_month(value)`
|
|
305
|
+
* **Описание:** Преобразовывает из любых форматов месяцев в числовом виде.
|
|
306
|
+
* **Возможности:** Поддерживает русский и английский языки.
|
|
307
|
+
|
|
308
|
+
### `take_weekday(value, start_zero, start_sunday)`
|
|
309
|
+
* **Описание:** Преобразует дни недели из любого формата в числовое значение.
|
|
310
|
+
* **Возможности:**
|
|
311
|
+
* Поддерживает русский и английский языки.
|
|
312
|
+
* Автоматически обрабатывает различные типы индексации дней недели.
|
|
313
|
+
|
|
314
|
+
### `distributor(s)`
|
|
315
|
+
* **Описание:** Конечный автомат, который создаёт значения из элементов строки в список.
|
|
316
|
+
* **Возможности:** Распределяет значения по стрелковому и числовому виду.
|
|
317
|
+
|
|
318
|
+
### `work_timezone1(value, to_tz, from_tz)`
|
|
319
|
+
* **Описание:** Переводит из одного часового пояса в другой и присваивает в конце результата конечный часовой пояс.
|
|
320
|
+
* **Возможности:** Поддерживает множество различных часовых поясов.
|
|
321
|
+
|
|
322
|
+
### `work_timezone2(value, keyword, to_tz, from_tz)`
|
|
323
|
+
* **Описание:** Преобразовывает из datetime объекта в строковой тип.
|
|
324
|
+
* **Возможности:** Результат зависит от параметров и определённого вида datetime объекта.
|
|
325
|
+
|
|
326
|
+
### `relative_datetime(value, keyword, *, current_date='now', current_time='now', current_datetime='now', from_tz=None, to_tz=None)`
|
|
327
|
+
* **Описание:** Преобразовывает из относительных строковых дат и времён в объект datetime.
|
|
328
|
+
* **Возможности:**
|
|
329
|
+
* Поддерживает русский и английский языки.
|
|
330
|
+
* Множество операций с относительными датами и временами.
|
|
331
|
+
|
|
332
|
+
### `make_date(value, *, order='ymd', current_date='now', century=21, start_sunday=False, start_zero=False)`
|
|
333
|
+
* **Описание:** Преобразовывает из различных форм строковых дат в объект datetime.
|
|
334
|
+
* **Возможности:**
|
|
335
|
+
* Поддерживает русский и английский языки.
|
|
336
|
+
* Поддержка текущей даты и прописывание любой даты для расчёта с остальными датами.
|
|
337
|
+
* Включает множество функционалов, в том числе внутренние функции relative_date, take_month, take_weekday.
|
|
338
|
+
* Обработка коротких записей годов благодаря параметру century.
|
|
339
|
+
* Расстановка положений года, месяца, дня, дня недели и нумерации недель.
|
|
340
|
+
|
|
341
|
+
### `make_time(value, *, order='HMS', current_time='now', from_tz=None, to_tz=None)`
|
|
342
|
+
* **Описание:** Преобразовывает из различных форм строковых времён в объект time.
|
|
343
|
+
* **Возможности:**
|
|
344
|
+
* Поддерживает русский и английский языки.
|
|
345
|
+
* Поддержка текущего времени и прописывание любого времени для расчёта с остальными временами.
|
|
346
|
+
* Включает множество функционалов, в том числе внутренние функции relative_datetime, work_timezone1, work_timezone2, distributor.
|
|
347
|
+
* Умная проверка диапазона единиц времени.
|
|
348
|
+
* Работа с часовыми поясами и автоматическое определение локального часового пояса.
|
|
349
|
+
|
|
350
|
+
### `make_datetime(value, *, order_date='ymd', order_time='HMS', century=21, isfirsttime=False, start_sunday=False, start_zero=False, current_datetime='now', from_tz=None, to_tz=None)`
|
|
351
|
+
* **Описание:** Преобразовывает из различных форм строковых дат + времён в объект datetime.
|
|
352
|
+
* **Возможности:**
|
|
353
|
+
* Поддерживает русский и английский языки.
|
|
354
|
+
* Поддержка текущих даты и времени и прописывание любых дат и времён для расчёта с остальными датами и временами.
|
|
355
|
+
* Включает множество функционалов, в том числе внутренние функции relative_datetime, make_date, make_time, work_timezone1 иwork_timezone2.
|