Testing a function that reads input and prints output
Replace input() and sys.stdout with unittest.mock.patch:
import io
from unittest.mock import patch
user_input = ['6 1']
expected_output = '...' # exactly what the function prints
with patch('builtins.input', side_effect=user_input):
with patch('sys.stdout', new=io.StringIO()) as output:
dodawanie(84, 7)
self.assertEqual(expected_output, output.getvalue())
More: How to test input processing in Python 3
Upgrade all outdated pip packages
(venv) $ pip list --outdated
(venv) $ pip list --outdated --format=freeze \
| grep -v '^\-e' | cut -d = -f 1 \
| xargs -n1 pip install -U
Source: How to upgrade all Python packages with pip
Reverse a string
txt = "Hello World"[::-1]
Save memory with generators
Generators return a lazy iterator instead of building the whole list in memory: Optimizing Memory Usage in Python Applications
Don’t write command-line menus, generate them
Instead of writing a command-line menu by hand, use hug or typer — it is like implementing a REST interface for your command-line program. See Don’t write command-line interfaces (generate them).
PySide2: open dialogs with exec()
window = QUiLoader().load("form/asset_ed.ui")
window.exec()
PySide2: iterate over files in resources
Compile the resource file:
pyside2-rcc resources.qrc > resources.py
Iterate over a resource directory:
import resources
it = QDirIterator(':/icon/icons8/')
while it.hasNext():
self.icon.addItem(QIcon(it.next()), '')
Dark theme for Jupyter Notebook
pip install jupyterthemes
jt -t monokai -fs 95 -altp -tfs 11 -nfs 115 -cellw 88% -T
Restore the default theme:
jt -r
Project: jupyter-themes
