fishertools 0.3.1__tar.gz → 0.3.4__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.
Files changed (122) hide show
  1. fishertools-0.3.4/PKG-INFO +859 -0
  2. fishertools-0.3.4/README.md +820 -0
  3. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/__init__.py +1 -1
  4. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/learn/__init__.py +17 -1
  5. fishertools-0.3.4/fishertools/learn/knowledge_engine.py +321 -0
  6. fishertools-0.3.4/fishertools/learn/test_knowledge_engine.py +241 -0
  7. fishertools-0.3.4/fishertools/learn/test_knowledge_engine_pbt.py +180 -0
  8. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/safe/__init__.py +2 -1
  9. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/safe/files.py +208 -0
  10. fishertools-0.3.4/fishertools.egg-info/PKG-INFO +859 -0
  11. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools.egg-info/SOURCES.txt +4 -0
  12. {fishertools-0.3.1 → fishertools-0.3.4}/pyproject.toml +1 -1
  13. {fishertools-0.3.1 → fishertools-0.3.4}/setup.py +1 -1
  14. fishertools-0.3.4/tests/test_readme_enhancements_v0_3_1.py +2036 -0
  15. fishertools-0.3.4/tests/test_safe/test_files.py +829 -0
  16. fishertools-0.3.1/PKG-INFO +0 -510
  17. fishertools-0.3.1/README.md +0 -471
  18. fishertools-0.3.1/fishertools.egg-info/PKG-INFO +0 -510
  19. fishertools-0.3.1/tests/test_safe/test_files.py +0 -222
  20. {fishertools-0.3.1 → fishertools-0.3.4}/LICENSE +0 -0
  21. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/config/__init__.py +0 -0
  22. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/config/manager.py +0 -0
  23. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/config/models.py +0 -0
  24. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/config/parser.py +0 -0
  25. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/decorators.py +0 -0
  26. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/documentation/__init__.py +0 -0
  27. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/documentation/api.py +0 -0
  28. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/documentation/generator.py +0 -0
  29. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/documentation/models.py +0 -0
  30. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/documentation/visual.py +0 -0
  31. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/errors/__init__.py +0 -0
  32. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/errors/exception_types.py +0 -0
  33. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/errors/exceptions.py +0 -0
  34. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/errors/explainer.py +0 -0
  35. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/errors/formatters.py +0 -0
  36. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/errors/models.py +0 -0
  37. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/errors/patterns.py +0 -0
  38. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/errors/recovery.py +0 -0
  39. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/examples/__init__.py +0 -0
  40. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/examples/cli_example.py +0 -0
  41. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/examples/learn_example.py +0 -0
  42. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/examples/logger_example.py +0 -0
  43. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/examples/menu_example.py +0 -0
  44. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/examples/models.py +0 -0
  45. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/examples/repository.py +0 -0
  46. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/examples/storage_example.py +0 -0
  47. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/helpers.py +0 -0
  48. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/input_utils.py +0 -0
  49. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/integration.py +0 -0
  50. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/learn/examples.py +0 -0
  51. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/learn/tips.py +0 -0
  52. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/learning/__init__.py +0 -0
  53. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/learning/core.py +0 -0
  54. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/learning/models.py +0 -0
  55. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/learning/progress.py +0 -0
  56. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/learning/session.py +0 -0
  57. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/learning/tutorial.py +0 -0
  58. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/legacy/__init__.py +0 -0
  59. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/legacy/deprecated.py +0 -0
  60. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/legacy/deprecation.py +0 -0
  61. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/patterns/__init__.py +0 -0
  62. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/patterns/cli.py +0 -0
  63. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/patterns/logger.py +0 -0
  64. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/patterns/menu.py +0 -0
  65. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/patterns/storage.py +0 -0
  66. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/readme_transformer.py +0 -0
  67. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/safe/collections.py +0 -0
  68. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/safe/strings.py +0 -0
  69. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/transform_readme.py +0 -0
  70. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools/utils.py +0 -0
  71. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools.egg-info/dependency_links.txt +0 -0
  72. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools.egg-info/requires.txt +0 -0
  73. {fishertools-0.3.1 → fishertools-0.3.4}/fishertools.egg-info/top_level.txt +0 -0
  74. {fishertools-0.3.1 → fishertools-0.3.4}/setup.cfg +0 -0
  75. {fishertools-0.3.1 → fishertools-0.3.4}/tests/__init__.py +0 -0
  76. {fishertools-0.3.1 → fishertools-0.3.4}/tests/conftest.py +0 -0
  77. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_config/__init__.py +0 -0
  78. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_config/test_basic_config.py +0 -0
  79. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_config/test_config_error_handling.py +0 -0
  80. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_config/test_config_properties.py +0 -0
  81. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_documentation/__init__.py +0 -0
  82. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_documentation/test_documentation_properties.py +0 -0
  83. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_documentation/test_visual_documentation_properties.py +0 -0
  84. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_errors/__init__.py +0 -0
  85. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_errors/test_api.py +0 -0
  86. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_errors/test_error_handling.py +0 -0
  87. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_errors/test_exception_types.py +0 -0
  88. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_errors/test_exception_types_pbt.py +0 -0
  89. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_errors/test_explainer.py +0 -0
  90. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_errors/test_formatters.py +0 -0
  91. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_errors/test_models.py +0 -0
  92. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_errors/test_patterns.py +0 -0
  93. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_examples/__init__.py +0 -0
  94. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_examples/test_example_repository_properties.py +0 -0
  95. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_examples/test_specific_examples.py +0 -0
  96. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_input_utils/__init__.py +0 -0
  97. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_input_utils/test_input_utils.py +0 -0
  98. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_integration.py +0 -0
  99. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_integration_enhancements.py +0 -0
  100. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_learn/__init__.py +0 -0
  101. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_learn/test_examples.py +0 -0
  102. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_learn/test_explain_properties.py +0 -0
  103. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_learn/test_tips.py +0 -0
  104. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_learning/__init__.py +0 -0
  105. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_learning/test_interactive_learning_properties.py +0 -0
  106. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_learning/test_learning_system_properties.py +0 -0
  107. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_learning/test_progress_tracking_properties.py +0 -0
  108. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_legacy/__init__.py +0 -0
  109. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_legacy/test_backward_compatibility.py +0 -0
  110. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_legacy/test_deprecation_warnings.py +0 -0
  111. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_patterns_cli.py +0 -0
  112. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_patterns_docstrings.py +0 -0
  113. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_patterns_logger.py +0 -0
  114. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_patterns_menu.py +0 -0
  115. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_patterns_storage.py +0 -0
  116. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_readme_transformer/__init__.py +0 -0
  117. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_readme_transformer/test_readme_infrastructure.py +0 -0
  118. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_readme_transformer/test_transform_readme_integration.py +0 -0
  119. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_safe/__init__.py +0 -0
  120. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_safe/test_collections_properties.py +0 -0
  121. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_structure.py +0 -0
  122. {fishertools-0.3.1 → fishertools-0.3.4}/tests/test_structure_enhancements.py +0 -0
@@ -0,0 +1,859 @@
1
+ Metadata-Version: 2.4
2
+ Name: fishertools
3
+ Version: 0.3.4
4
+ Summary: Fishertools - инструменты, которые делают Python удобнее и безопаснее для новичков
5
+ Home-page: https://github.com/f1sherFM/My_1st_library_python
6
+ Author: f1sherFM
7
+ Author-email: f1sherFM <kirillka229top@gmail.com>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/f1sherFM/My_1st_library_python
10
+ Project-URL: Repository, https://github.com/f1sherFM/My_1st_library_python
11
+ Project-URL: Issues, https://github.com/f1sherFM/My_1st_library_python/issues
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Requires-Python: >=3.8
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: requests>=2.25.0
28
+ Requires-Dist: click>=8.0.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
31
+ Requires-Dist: hypothesis>=6.0.0; extra == "dev"
32
+ Requires-Dist: black>=24.0.0; extra == "dev"
33
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
34
+ Requires-Dist: mypy>=1.8.0; extra == "dev"
35
+ Dynamic: author
36
+ Dynamic: home-page
37
+ Dynamic: license-file
38
+ Dynamic: requires-python
39
+
40
+ **Инструменты, которые делают Python удобнее и безопаснее для новичков**
41
+ ```bash
42
+ pip install fishertools
43
+ ```
44
+ | Задача | Что вызвать |
45
+ |--------|-------------|
46
+ | Объяснить ошибку | explain_error(e) |
47
+ | Красиво показать traceback | explain_error(e) |
48
+ | Безопасно читать файл | safe_read_file(path) |
49
+ ## Для кого эта библиотека
50
+
51
+ - Ты только начал изучать Python
52
+ - Сообщения об ошибках кажутся страшными и непонятными
53
+ - Хочешь, чтобы ошибки объяснялись на нормальном русском с примерами
54
+ # Fishertools
55
+
56
+ **Инструменты, которые делают Python удобнее и безопаснее для новичков**
57
+
58
+ Fishertools - это Python библиотека, созданная специально для начинающих разработчиков. Она предоставляет понятные объяснения ошибок, безопасные утилиты и обучающие инструменты.
59
+
60
+ ## 🎯 Основные возможности
61
+
62
+ ### 🚨 Объяснение ошибок Python
63
+ Получайте понятные объяснения ошибок на русском языке с советами по исправлению:
64
+
65
+ ```python
66
+ from fishertools import explain_error
67
+
68
+ try:
69
+ numbers = [1, 2, 3]
70
+ print(numbers[10])
71
+ except Exception as e:
72
+ explain_error(e)
73
+ ```
74
+
75
+ **Вывод:**
76
+ ```
77
+ 🚨 Ошибка Python: IndexError
78
+
79
+ ═══ Сообщение об ошибке ═══
80
+ list index out of range
81
+
82
+ ═══ Что это означает ═══
83
+ Вы пытаетесь получить элемент списка по индексу, которого не существует.
84
+ Индексы в Python начинаются с 0, а максимальный индекс равен длине списка минус 1.
85
+
86
+ ═══ Как исправить ═══
87
+ Проверьте длину списка перед обращением к элементу или используйте
88
+ безопасные методы получения элементов.
89
+
90
+ ═══ Пример ═══
91
+ ┌─ Правильный код ─┐
92
+ numbers = [1, 2, 3]
93
+ if len(numbers) > 10:
94
+ print(numbers[10])
95
+ else:
96
+ print("Индекс слишком большой!")
97
+ └───────────────────┘
98
+ ```
99
+
100
+ ### Примеры других ошибок
101
+
102
+ #### NameError: имя не определено
103
+
104
+ ```python
105
+ from fishertools import explain_error
106
+
107
+ try:
108
+ print(result)
109
+ except Exception as e:
110
+ explain_error(e)
111
+ ```
112
+ ### Возможный вывод:
113
+ ```
114
+ 🚨 Ошибка Python: NameError
115
+
116
+ ═══ Сообщение об ошибке ═══
117
+ name 'result' is not defined
118
+
119
+ ═══ Что это означает ═══
120
+ В коде используется переменная или имя, которое ещё не было объявлено.
121
+ Чаще всего это опечатка или переменная создана в другом месте.
122
+
123
+ ═══ Как исправить ═══
124
+ Проверьте, правильно ли написано имя переменной и объявлена ли она
125
+ до использования.
126
+
127
+ ═══ Пример ═══
128
+ ┌─ Правильный код ─┐
129
+ result = 42
130
+ print(result)
131
+ ```
132
+
133
+ TypeError: нельзя сложить число и строку
134
+ ```python
135
+ from fishertools import explain_error
136
+
137
+ try:
138
+ age = 18
139
+ message = "Мне " + age + " лет"
140
+ except Exception as e:
141
+ explain_error(e)
142
+ ```
143
+ ### Возможный вывод:
144
+ ```
145
+ 🚨 Ошибка Python: TypeError
146
+
147
+ ═══ Сообщение об ошибке ═══
148
+ can only concatenate str (not "int") to str
149
+
150
+ ═══ Что это означает ═══
151
+ Вы пытаетесь выполнить операцию над значениями разных типов
152
+ (например, сложить строку и число).
153
+
154
+ ═══ Как исправить ═══
155
+ Приведите значение к нужному типу или используйте форматирование строки.
156
+
157
+ ═══ Пример ═══
158
+ ┌─ Правильный код ─┐
159
+ age = 18
160
+ message = f"Мне {age} лет"
161
+ print(message)
162
+ └───────────────────┘
163
+ ```
164
+
165
+
166
+ ### 🛡️ Безопасные утилиты
167
+ Функции, которые предотвращают типичные ошибки новичков:
168
+
169
+ ```python
170
+ from fishertools.safe import safe_get, safe_divide, safe_read_file, ensure_dir, get_file_hash, read_last_lines
171
+
172
+ # Безопасное получение элемента
173
+ numbers = [1, 2, 3]
174
+ result = safe_get(numbers, 10, "не найден") # "не найден"
175
+
176
+ # Безопасное деление
177
+ result = safe_divide(10, 0, 0) # 0 вместо ошибки
178
+
179
+ # Безопасное чтение файла
180
+ content = safe_read_file("file.txt", default="файл не найден")
181
+
182
+ # Рекурсивное создание директорий
183
+ path = ensure_dir("./data/nested/directory") # Создаст все промежуточные папки
184
+
185
+ # Вычисление хэша файла
186
+ file_hash = get_file_hash("data.txt") # SHA256 по умолчанию
187
+ md5_hash = get_file_hash("data.txt", algorithm='md5')
188
+
189
+ # Чтение последних строк файла
190
+ last_lines = read_last_lines("log.txt", n=10) # Последние 10 строк
191
+ ```
192
+
193
+ ### 📚 Обучающие инструменты
194
+ Изучайте Python на примерах и лучших практиках:
195
+
196
+ ```python
197
+ from fishertools.learn import show_best_practice, generate_example
198
+
199
+ # Показать лучшие практики
200
+ show_best_practice("variables")
201
+
202
+ # Сгенерировать пример кода
203
+ example = generate_example("functions")
204
+ print(example)
205
+ ```
206
+
207
+ ### 🎓 Объяснение Python концепций
208
+ Получайте структурированные объяснения Python тем с примерами:
209
+
210
+ ```python
211
+ from fishertools.learn import explain
212
+
213
+ # Получить объяснение темы
214
+ explanation = explain("list")
215
+ print(explanation["description"])
216
+ print(explanation["when_to_use"])
217
+ print(explanation["example"])
218
+ ```
219
+
220
+ ### 🔧 Готовые паттерны
221
+ Используйте готовые шаблоны для типичных задач:
222
+
223
+ ```python
224
+ from fishertools.patterns import simple_menu, JSONStorage, SimpleLogger, SimpleCLI
225
+
226
+ # Интерактивное меню
227
+ simple_menu({
228
+ "Опция 1": lambda: print("Выбрана опция 1"),
229
+ "Опция 2": lambda: print("Выбрана опция 2")
230
+ })
231
+
232
+ # Сохранение данных в JSON
233
+ storage = JSONStorage("data.json")
234
+ storage.save({"name": "Alice", "age": 30})
235
+
236
+ # Логирование
237
+ logger = SimpleLogger("app.log")
238
+ logger.info("Приложение запущено")
239
+
240
+ # CLI приложение
241
+ cli = SimpleCLI("myapp", "Мое приложение")
242
+ @cli.command("greet", "Поздравить пользователя")
243
+ def greet(name):
244
+ print(f"Привет, {name}!")
245
+ cli.run()
246
+ ```
247
+
248
+ ### 🔄 Обратная совместимость
249
+ Все полезные функции из предыдущих версий сохранены:
250
+
251
+ ```python
252
+ from fishertools.legacy import hash_string, generate_password, QuickConfig
253
+
254
+ # Старые функции работают как прежде
255
+ password = generate_password(12)
256
+ hash_value = hash_string("my_string")
257
+ config = QuickConfig({"debug": True})
258
+ ```
259
+
260
+ ## 📦 Установка
261
+
262
+ ### Текущий статус версии
263
+
264
+ ⚠️ **Важно:** Версия 0.3.1 ещё не опубликована на PyPI. Последняя версия на PyPI - это 0.2.1.
265
+
266
+ Для установки версии 0.3.1 используйте один из следующих способов:
267
+
268
+ ### Установка из исходников
269
+
270
+ ```bash
271
+ git clone https://github.com/f1sherFM/My_1st_library_python.git
272
+ cd My_1st_library_python
273
+ pip install -e .
274
+ ```
275
+
276
+ ### Установка последней версии с PyPI (v0.2.1)
277
+
278
+ ```bash
279
+ pip install fishertools
280
+ ```
281
+
282
+ ### Установка для разработки
283
+
284
+ ```bash
285
+ git clone https://github.com/f1sherFM/My_1st_library_python.git
286
+ cd My_1st_library_python
287
+ pip install -e ".[dev]"
288
+ ```
289
+
290
+ **Примечание:** Версия 0.3.1 будет опубликована на PyPI после завершения тестирования и финализации документации.
291
+
292
+ ## 🚀 Быстрый старт
293
+
294
+ ```python
295
+ from fishertools import explain_error
296
+
297
+ # Основная функция - объяснение ошибок
298
+ try:
299
+ result = 10 / 0
300
+ except Exception as e:
301
+ explain_error(e)
302
+
303
+ # Безопасные утилиты
304
+ from fishertools.safe import safe_get, safe_divide
305
+ safe_result = safe_get([1, 2, 3], 5, "default")
306
+
307
+ # Обучающие инструменты
308
+ from fishertools.learn import show_best_practice
309
+ show_best_practice("functions")
310
+ ```
311
+
312
+ ## 📚 Обучающие инструменты v0.3.1
313
+
314
+ ### Knowledge Engine - Образовательная система для Python
315
+
316
+ Knowledge Engine предоставляет структурированные объяснения 35+ Python концепций для новичков с примерами, типичными ошибками и связанными темами:
317
+
318
+ ```python
319
+ from fishertools.learn import get_topic, list_topics, search_topics, get_learning_path
320
+
321
+ # Получить информацию о теме
322
+ topic = get_topic("Lists")
323
+ print(topic["description"]) # Описание
324
+ print(topic["when_to_use"]) # Когда использовать
325
+ print(topic["example"]) # Пример кода
326
+ print(topic["common_mistakes"]) # Типичные ошибки
327
+
328
+ # Получить список всех тем
329
+ all_topics = list_topics()
330
+ print(f"Всего тем: {len(all_topics)}")
331
+
332
+ # Поиск по ключевому слову
333
+ results = search_topics("loop")
334
+ print(f"Найдено тем о циклах: {len(results)}")
335
+
336
+ # Получить рекомендуемый путь обучения
337
+ learning_path = get_learning_path()
338
+ for i, topic_name in enumerate(learning_path[:5], 1):
339
+ print(f"{i}. {topic_name}")
340
+ ```
341
+
342
+ **Структура темы:**
343
+
344
+ ```python
345
+ {
346
+ "topic": "Lists",
347
+ "category": "Collections",
348
+ "description": "Ordered collections of items...",
349
+ "when_to_use": "Use lists when you need to store multiple items...",
350
+ "example": "fruits = ['apple', 'banana']\nprint(fruits[0])",
351
+ "common_mistakes": ["Forgetting that indexing starts at 0", ...],
352
+ "related_topics": ["List Indexing", "List Slicing", ...],
353
+ "difficulty": "beginner",
354
+ "order": 6
355
+ }
356
+ ```
357
+
358
+ **Категории тем (35 тем всего):**
359
+
360
+ - **Basic Types** (5 тем): Variables, Integers, Strings, Booleans, Type Conversion
361
+ - **Collections** (6 тем): Lists, List Indexing, List Slicing, Dictionaries, Tuples, Sets
362
+ - **Control Flow** (5 тем): If Statements, Comparison Operators, Logical Operators, For Loops, While Loops
363
+ - **Functions** (5 тем): Function Definition, Parameters, Return Statements, Default Parameters, Variable Scope
364
+ - **String Operations** (4 темы): String Methods, Formatting, Concatenation, Indexing
365
+ - **File Operations** (3 темы): Reading Files, Writing Files, File Paths
366
+ - **Error Handling** (3 темы): Try-Except Blocks, Common Exceptions, Raising Exceptions
367
+ - **Advanced Basics** (4 темы): List Comprehensions, Lambda Functions, Map and Filter, Enumerate
368
+
369
+ ### Объяснение Python концепций с помощью explain()
370
+
371
+ Функция `explain()` предоставляет структурированные объяснения для 30+ Python тем с примерами кода:
372
+
373
+ ```python
374
+ from fishertools.learn import explain
375
+
376
+ # Получить объяснение темы
377
+ explanation = explain("list")
378
+ print(explanation["description"]) # Что это такое
379
+ print(explanation["when_to_use"]) # Когда использовать
380
+ print(explanation["example"]) # Пример кода
381
+ ```
382
+
383
+ ### Структура данных explain()
384
+
385
+ Функция `explain()` возвращает словарь с тремя ключами, содержащими полную информацию о теме:
386
+
387
+ ```python
388
+ from fishertools.learn import explain
389
+
390
+ explanation = explain("list")
391
+ print(explanation)
392
+ # {
393
+ # "description": "Ordered collection of items that can be of different types. Lists are mutable, meaning you can add, remove, or modify items.",
394
+ # "when_to_use": "Use lists when you need to store multiple items in order and may need to modify them later. Perfect for storing collections of data.",
395
+ # "example": "fruits = [\"apple\", \"banana\", \"orange\"]\nfruits.append(\"grape\")\nprint(fruits[0])\nprint(len(fruits))\nfor fruit in fruits:\n print(fruit)"
396
+ # }
397
+ ```
398
+
399
+ **Доступ к полям:**
400
+
401
+ ```python
402
+ from fishertools.learn import explain
403
+
404
+ explanation = explain("list")
405
+
406
+ # Получить описание
407
+ print(explanation["description"])
408
+ # Ordered collection of items that can be of different types...
409
+
410
+ # Получить информацию о применении
411
+ print(explanation["when_to_use"])
412
+ # Use lists when you need to store multiple items in order...
413
+
414
+ # Получить пример кода
415
+ print(explanation["example"])
416
+ # fruits = ["apple", "banana", "orange"]
417
+ # fruits.append("grape")
418
+ # print(fruits[0])
419
+ # ...
420
+ ```
421
+
422
+ ### Поддерживаемые темы
423
+
424
+ | Категория | Тема | Описание |
425
+ |-----------|------|---------|
426
+ | **Типы данных** | int | Integer data type for whole numbers without decimals. Integers can be positive, negative, or zero. |
427
+ | **Типы данных** | float | Floating-point data type for numbers with decimal places. Floats represent real numbers with fractional parts. |
428
+ | **Типы данных** | str | String data type for text. Strings are sequences of characters enclosed in quotes (single, double, or triple). |
429
+ | **Типы данных** | bool | Boolean data type with only two possible values: True or False. Used for logical operations and conditions. |
430
+ | **Типы данных** | list | Ordered collection of items that can be of different types. Lists are mutable, meaning you can add, remove, or modify items. |
431
+ | **Типы данных** | tuple | Ordered collection of items similar to lists, but immutable. Once created, tuples cannot be modified. |
432
+ | **Типы данных** | set | Unordered collection of unique items. Sets automatically remove duplicates and are useful for membership testing. |
433
+ | **Типы данных** | dict | Unordered collection of key-value pairs. Dictionaries allow you to store and retrieve data using meaningful keys instead of numeric indices. |
434
+ | **Управляющие конструкции** | if | Conditional statement that executes code only if a condition is true. Forms the basis of decision-making in programs. |
435
+ | **Управляющие конструкции** | for | Loop statement that iterates over a sequence (list, tuple, string, etc.) and executes code for each item. |
436
+ | **Управляющие конструкции** | while | Loop statement that repeatedly executes code as long as a condition is true. Useful when you don't know how many iterations you need. |
437
+ | **Управляющие конструкции** | break | Statement that immediately exits the current loop, skipping any remaining iterations. |
438
+ | **Управляющие конструкции** | continue | Statement that skips the current iteration of a loop and moves to the next iteration. |
439
+ | **Функции** | function | Reusable block of code that performs a specific task. Functions help organize code and avoid repetition. |
440
+ | **Функции** | return | Statement that sends a value back from a function to the caller. A function can return any type of data. |
441
+ | **Функции** | lambda | Anonymous function defined with a single expression. Lambdas are useful for short, simple functions. |
442
+ | **Функции** | *args | Special parameter that allows a function to accept any number of positional arguments as a tuple. |
443
+ | **Функции** | **kwargs | Special parameter that allows a function to accept any number of keyword arguments as a dictionary. |
444
+ | **Обработка ошибок** | try | Statement that begins a block of code where exceptions might occur. Used with except to handle errors gracefully. |
445
+ | **Обработка ошибок** | except | Statement that catches and handles specific exceptions that occur in a try block. |
446
+ | **Обработка ошибок** | finally | Statement that executes code after try and except blocks, regardless of whether an exception occurred. |
447
+ | **Обработка ошибок** | raise | Statement that manually raises an exception to signal an error condition in your code. |
448
+ | **Работа с файлами** | open | Function that opens a file and returns a file object. Used to read from or write to files. |
449
+ | **Работа с файлами** | read | Method that reads the entire contents of a file as a string, or reads a specific number of characters. |
450
+ | **Работа с файлами** | write | Method that writes data to a file. Creates the file if it doesn't exist, or overwrites it if it does. |
451
+ | **Работа с файлами** | with | Context manager statement that automatically handles resource management, ensuring files are properly closed. |
452
+ | **Типы данных** | slice | Technique to extract a portion of a sequence (list, tuple, string) using start:stop:step notation. |
453
+ | **Типы данных** | list_comprehension | Concise way to create a new list by applying an expression to each item in an existing sequence. |
454
+ | **Типы данных** | enumerate | Built-in function that returns both the index and value when iterating over a sequence. |
455
+ | **Управляющие конструкции** | import | Statement that loads a module or specific items from a module into your program. Modules contain reusable code. |
456
+
457
+ **Пример использования:**
458
+
459
+ ```python
460
+ from fishertools.learn import explain
461
+
462
+ # Объяснение списков
463
+ list_info = explain("list")
464
+ print(list_info)
465
+ # {
466
+ # "description": "Упорядоченная коллекция элементов",
467
+ # "when_to_use": "Используйте, когда нужно хранить несколько элементов в порядке",
468
+ # "example": "items = [1, 2, 3]\nitems.append(4)\nprint(items[0])"
469
+ # }
470
+
471
+ # Объяснение цикла for
472
+ for_info = explain("for")
473
+ print(for_info["example"])
474
+ ```
475
+
476
+ ### Расширение и локализация
477
+
478
+ Все темы хранятся в JSON файле `fishertools/learn/explanations.json`, что делает их легко расширяемыми и локализуемыми:
479
+
480
+ **Для контрибьюторов:**
481
+ - Добавьте новую тему в JSON файл `fishertools/learn/explanations.json`
482
+ - Каждая тема должна содержать три поля: `description`, `when_to_use`, и `example`
483
+ - Функция `explain()` автоматически загружает все темы из этого файла
484
+
485
+ **Для локализации:**
486
+ - Переведите существующие темы на другой язык
487
+ - Создайте новый JSON файл с переводами
488
+ - Используйте параметр `language` при вызове `explain()` для выбора языка
489
+
490
+ **Для кастомизации:**
491
+ - Используйте свой JSON файл с дополнительными темами
492
+ - Передайте путь к файлу при инициализации модуля
493
+ - Это позволяет добавлять специфичные для вашего проекта темы
494
+
495
+ Благодаря JSON-хранилищу, расширение fishertools не требует изменения кода - просто добавьте новые записи в JSON файл!
496
+
497
+ ### Готовые паттерны для типичных задач
498
+
499
+ Модуль `fishertools.patterns` предоставляет готовые шаблоны для типичных программных задач.
500
+
501
+ #### 1. simple_menu() - Интерактивное меню
502
+
503
+ Создавайте интерактивные консольные меню без лишнего кода:
504
+
505
+ ```python
506
+ from fishertools.patterns import simple_menu
507
+
508
+ def show_greeting():
509
+ print("Привет! 👋")
510
+
511
+ def show_goodbye():
512
+ print("До свидания! 👋")
513
+
514
+ def show_help():
515
+ print("Это справка по приложению")
516
+
517
+ simple_menu({
518
+ "Поздравить": show_greeting,
519
+ "Попрощаться": show_goodbye,
520
+ "Справка": show_help
521
+ })
522
+ ```
523
+
524
+ **Особенности:**
525
+ - Автоматическая нумерация опций
526
+ - Обработка некорректного ввода
527
+ - Команды "quit" и "exit" для выхода
528
+ - Повторный запрос при ошибке
529
+
530
+ #### 2. JSONStorage - Сохранение данных
531
+
532
+ Сохраняйте и загружайте данные в JSON без обработки ошибок:
533
+
534
+ ```python
535
+ from fishertools.patterns import JSONStorage
536
+
537
+ # Создание хранилища
538
+ storage = JSONStorage("users.json")
539
+
540
+ # Сохранение данных
541
+ users = [
542
+ {"name": "Alice", "age": 30},
543
+ {"name": "Bob", "age": 25}
544
+ ]
545
+ storage.save(users)
546
+
547
+ # Загрузка данных
548
+ loaded_users = storage.load()
549
+ print(loaded_users)
550
+
551
+ # Проверка существования файла
552
+ if storage.exists():
553
+ print("Файл существует")
554
+ ```
555
+
556
+ **Особенности:**
557
+ - Автоматическое создание директорий
558
+ - Автоматическое создание файла при сохранении
559
+ - Обработка ошибок файловых операций
560
+ - Простой API для сохранения/загрузки
561
+
562
+ #### 3. SimpleLogger - Логирование
563
+
564
+ Добавляйте логирование в приложение с временными метками:
565
+
566
+ ```python
567
+ from fishertools.patterns import SimpleLogger
568
+
569
+ # Создание логгера
570
+ logger = SimpleLogger("app.log")
571
+
572
+ # Логирование сообщений
573
+ logger.info("Приложение запущено")
574
+ logger.warning("Низкий уровень памяти")
575
+ logger.error("Ошибка подключения")
576
+ ```
577
+
578
+ **Формат логов:**
579
+ ```
580
+ [2024-01-15 10:30:45] [INFO] Приложение запущено
581
+ [2024-01-15 10:30:46] [WARNING] Низкий уровень памяти
582
+ [2024-01-15 10:30:47] [ERROR] Ошибка подключения
583
+ ```
584
+
585
+ **Особенности:**
586
+ - Автоматические временные метки
587
+ - Три уровня логирования: INFO, WARNING, ERROR
588
+ - Автоматическое создание файла логов
589
+ - Добавление к существующему файлу
590
+
591
+ #### 4. SimpleCLI - Командная строка
592
+
593
+ Создавайте CLI приложения с минимальным кодом:
594
+
595
+ ```python
596
+ from fishertools.patterns import SimpleCLI
597
+
598
+ # Создание CLI приложения
599
+ cli = SimpleCLI("myapp", "Мое приложение")
600
+
601
+ # Регистрация команд через декоратор
602
+ @cli.command("greet", "Поздравить пользователя")
603
+ def greet(name):
604
+ print(f"Привет, {name}!")
605
+
606
+ @cli.command("add", "Сложить два числа")
607
+ def add(a, b):
608
+ result = int(a) + int(b)
609
+ print(f"Результат: {result}")
610
+
611
+ # Запуск приложения
612
+ if __name__ == "__main__":
613
+ cli.run()
614
+ ```
615
+
616
+ **Использование:**
617
+ ```bash
618
+ python myapp.py greet Alice
619
+ # Привет, Alice!
620
+
621
+ python myapp.py add 5 3
622
+ # Результат: 8
623
+
624
+ python myapp.py --help
625
+ # Показать все доступные команды
626
+ ```
627
+
628
+ **Особенности:**
629
+ - Регистрация команд через декоратор
630
+ - Автоматический парсинг аргументов
631
+ - Встроенная справка (--help)
632
+ - Обработка неправильных команд
633
+
634
+ ### Примеры использования
635
+
636
+ Полные примеры использования всех компонентов находятся в директории `fishertools/examples/`:
637
+
638
+ - `learn_example.py` - Примеры использования explain()
639
+ - `menu_example.py` - Примеры simple_menu()
640
+ - `storage_example.py` - Примеры JSONStorage
641
+ - `logger_example.py` - Примеры SimpleLogger
642
+ - `cli_example.py` - Примеры SimpleCLI
643
+
644
+ Вы можете запустить любой пример:
645
+ ```bash
646
+ python -m fishertools.examples.learn_example
647
+ python -m fishertools.examples.menu_example
648
+ python -m fishertools.examples.storage_example
649
+ python -m fishertools.examples.logger_example
650
+ python -m fishertools.examples.cli_example
651
+ ```
652
+
653
+ ## 📖 Документация
654
+
655
+ ### Поддерживаемые типы ошибок
656
+
657
+ Fishertools объясняет следующие типы ошибок Python. Это полный список поддерживаемых типов ошибок:
658
+
659
+ #### Ошибки типов и значений
660
+
661
+ - **TypeError** - возникает при попытке выполнить операцию над значениями несовместимых типов (например, сложить число и строку)
662
+ - **ValueError** - возникает когда функция получает аргумент правильного типа, но неправильного значения (например, int("abc"))
663
+
664
+ #### Ошибки доступа к данным
665
+
666
+ - **AttributeError** - возникает при попытке доступа к несуществующему атрибуту объекта
667
+ - **IndexError** - возникает при попытке доступа к элементу списка по индексу, который выходит за границы списка
668
+ - **KeyError** - возникает при попытке доступа к несуществующему ключу в словаре
669
+
670
+ #### Ошибки импорта и синтаксиса
671
+
672
+ - **ImportError** - возникает при проблемах с импортом модулей (модуль не найден или ошибка в модуле)
673
+ - **SyntaxError** - возникает при синтаксических ошибках в коде (неправильный синтаксис Python)
674
+
675
+ #### Ошибки имён и вычислений
676
+
677
+ - **NameError** - возникает при использовании переменной или имени, которое не было определено
678
+ - **ZeroDivisionError** - возникает при попытке деления на ноль
679
+
680
+ #### Ошибки файловой системы
681
+
682
+ - **FileNotFoundError** - возникает при попытке открыть файл, который не существует
683
+
684
+ **Примеры использования:**
685
+
686
+ ```python
687
+ from fishertools import explain_error
688
+
689
+ # Пример 1: TypeError
690
+ try:
691
+ result = "5" + 10
692
+ except Exception as e:
693
+ explain_error(e)
694
+
695
+ # Пример 2: ValueError
696
+ try:
697
+ number = int("abc")
698
+ except Exception as e:
699
+ explain_error(e)
700
+
701
+ # Пример 3: IndexError
702
+ try:
703
+ items = [1, 2, 3]
704
+ print(items[10])
705
+ except Exception as e:
706
+ explain_error(e)
707
+
708
+ # Пример 4: KeyError
709
+ try:
710
+ data = {"name": "Alice"}
711
+ print(data["age"])
712
+ except Exception as e:
713
+ explain_error(e)
714
+
715
+ # Пример 5: FileNotFoundError
716
+ try:
717
+ with open("nonexistent.txt") as f:
718
+ content = f.read()
719
+ except Exception as e:
720
+ explain_error(e)
721
+ ```
722
+
723
+ ### Безопасные утилиты
724
+
725
+ - `safe_get(collection, index, default)` - безопасное получение элемента
726
+ - `safe_divide(a, b, default)` - деление без ошибки на ноль
727
+ - `safe_max(collection, default)` - максимум из коллекции
728
+ - `safe_min(collection, default)` - минимум из коллекции
729
+ - `safe_sum(collection, default)` - сумма элементов
730
+ - `safe_read_file(path, default)` - чтение файла без ошибок
731
+ - `ensure_dir(path)` - рекурсивное создание директорий
732
+ - `get_file_hash(path, algorithm='sha256')` - вычисление хэша файла
733
+ - `read_last_lines(path, n=10)` - чтение последних N строк файла
734
+
735
+ ### Обучающие функции
736
+
737
+ - `show_best_practice(topic)` - показать лучшие практики
738
+ - `generate_example(concept)` - сгенерировать пример кода
739
+ - `list_available_concepts()` - список доступных концепций
740
+ - `list_available_topics()` - список доступных тем
741
+
742
+ ## ⚠️ Ограничения
743
+
744
+ Текущая версия fishertools имеет следующие известные ограничения:
745
+
746
+ ### explain_error() и SyntaxError
747
+
748
+ `explain_error()` не может объяснить `SyntaxError` до исполнения кода. Это связано с тем, что синтаксические ошибки обнаруживаются на этапе парсинга (анализа кода), который происходит **до** выполнения программы. Это означает, что вы не сможете поймать `SyntaxError` в блоке `try-except`, так как программа не будет запущена вообще.
749
+
750
+ **Пример:**
751
+ ```python
752
+ # Это вызовет SyntaxError ДО выполнения программы
753
+ try:
754
+ x = 5 + # Синтаксическая ошибка - неполное выражение
755
+ except SyntaxError as e:
756
+ explain_error(e) # Этот код никогда не выполнится
757
+ ```
758
+
759
+ Однако вы можете объяснить другие типы ошибок, которые возникают во время выполнения:
760
+ ```python
761
+ # Это работает - ошибка возникает во время выполнения
762
+ try:
763
+ result = 10 / 0 # ZeroDivisionError
764
+ except Exception as e:
765
+ explain_error(e) # Работает корректно
766
+ ```
767
+
768
+ ### explain() и объектно-ориентированное программирование
769
+
770
+ Функция `explain()` пока не поддерживает объяснение классов и концепций OOP (объектно-ориентированного программирования), таких как:
771
+ - Классы и объекты
772
+ - Наследование
773
+ - Полиморфизм
774
+ - Инкапсуляция
775
+ - Методы и свойства класса
776
+
777
+ Поддержка OOP планируется в будущих версиях fishertools. На данный момент `explain()` работает с базовыми типами данных и управляющими конструкциями.
778
+
779
+ **Текущие возможности explain():**
780
+ ```python
781
+ from fishertools.learn import explain
782
+
783
+ # Это работает
784
+ explain("list") # Типы данных
785
+ explain("for") # Управляющие конструкции
786
+ explain("function") # Функции
787
+ explain("try") # Обработка ошибок
788
+
789
+ # Это пока не поддерживается
790
+ # explain("class") # Классы
791
+ # explain("inheritance") # Наследование
792
+ # explain("polymorphism") # Полиморфизм
793
+ ```
794
+
795
+ ## 🧪 Тестирование
796
+
797
+ Библиотека покрыта comprehensive тестами:
798
+
799
+ ```bash
800
+ # Запуск всех тестов
801
+ pytest
802
+
803
+ # Запуск property-based тестов
804
+ pytest -k "property"
805
+
806
+ # Запуск с покрытием
807
+ pytest --cov=fishertools
808
+ ```
809
+
810
+ ## 🛠️ Разработка
811
+
812
+ ```bash
813
+ # Установка для разработки
814
+ pip install -e ".[dev]"
815
+
816
+ # Форматирование кода
817
+ black fishertools tests
818
+
819
+ # Проверка типов
820
+ mypy fishertools
821
+
822
+ # Линтинг
823
+ ruff check fishertools
824
+ ```
825
+
826
+ ## 📋 Требования
827
+
828
+ - Python 3.8+
829
+ - requests >= 2.25.0
830
+ - click >= 8.0.0
831
+
832
+ Для разработки:
833
+ - pytest >= 8.0.0
834
+ - hypothesis >= 6.0.0 (для property-based тестов)
835
+ - black >= 24.0.0
836
+ - ruff >= 0.1.0
837
+ - mypy >= 1.8.0
838
+
839
+ ## 🤝 Вклад в проект
840
+
841
+ Мы приветствуем вклад в развитие проекта! Пожалуйста:
842
+
843
+ 1. Форкните репозиторий
844
+ 2. Создайте ветку для новой функции
845
+ 3. Добавьте тесты для новой функциональности
846
+ 4. Убедитесь, что все тесты проходят
847
+ 5. Создайте Pull Request
848
+
849
+ ## 📄 Лицензия
850
+
851
+ MIT License - см. файл [LICENSE](LICENSE)
852
+
853
+ ## 🙏 Благодарности
854
+
855
+ Спасибо всем, кто помогает делать Python более доступным для новичков!
856
+
857
+ ---
858
+
859
+ **Fishertools** - потому что каждый заслуживает понятные инструменты для изучения программирования! 🐍✨