Python
Syntax#
Python has no end if
or code blocks, for the visual appearance, We can use #endif
to make clear that the if ends.
iterators#
iterate once#
A filter is a special iterable object you can iterate over. However, much like a generator, you can iterate over it only once. So, by calling list(filtered)
, you are iterating over each element of the filter object to generate the list. At this point, you've reached the end of the iterable and nothing more to return.
e.g.
1 2 3 4 5 6 7 8 9 |
|
performance#
Use any()+comprehension
#
Instead of any()+lambda
The reason is that you've passed a generator expression to the
any()
function. Python needs to convert your generator expression to a generator function and that's why it performs slower. Because a generator function needs to call the__next__()
method each time for generating the item and passing it to the any. This is while in a manual defined function you are passing the whole list to your function which has all the items prepared already. Also another bottleneck in your code which has more cost than extra calls on next is the way you do the comparison. As mentioned in comment the better equivalent of your manual function is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
syntax#
filter map
1 2 3 4 5 6 7 8 9 |
|
reduce
operators#
Walrus Operator#
「命名表达式」,别名「海象运算符」
因为 :=
很像海象「眼睛小,长着两枚长长的牙」这个特点
有点可爱
list/array#
traverse#
d = {'name1' : 'pythontab', 'name2' : '.', 'name3' : 'com'} for key in d: print (key, ' value : ', d[key])
functions#
function must be claimed before access. return is not compulsory.
lambda function#
tag:匿名函数 lambda 函数的语法只包含一个语句,如下: lambda arg1,arg2,.....argn:expression(主要是看下面的例子)
1 2 3 4 5 6 7 8 9 10 |
|
random function#
1 2 3 4 5 6 7 8 |
|
custom classes#
__new__
and __instance__
#
cannot inherit from int#
Because all classes are derived from object
and object
is an abstract class, you cannot inherit from int
.
in __init__(self)
, if set self=1. in other functions, print(self) is still not 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
code style#
we are obligated (not obliged) to use 4 spaces indent (by black, autopep8). merge loops use array.
logic control#
1 2 3 4 5 |
|
debugging#
python unresolved import vscode
1 2 3 4 |
|
Python typing#
- @2021-12-15
- Python Typing - Type Hints & Annotations explains how python types, although it is for Python3.8.
- Not easy part is generic type and callable type.
- There's no "non-null assertion" in python, but inline if statement is a way to do it. details
Python 3.10 new features#
- @2021-12-15
- Official: What’s New In Python 3.10
- Youtube: New Features In Python 3.10 You Should Know with chapters, clean and short (succinct).
- Youtube, for
match
: https://www.youtube.com/watch?v=-79HGfWmH_w&ab_channel=mCoding more details ofmatch
.
Python version control#
- @2021-12-16
- It seems current best solution is to use pyenv. It's like
nvm
for node. - @2021-12-20
- uninstall old versions
Install Python(Mac)#
- @2021-12-16
- It's better to install with brew.
Class diagram in Python#
- @2021-12-16
- GodBa said
I never draw UML diagram after leaving school
. Usually python developers don't draw it that's probably the reason you can't find a good one
- Most links in What's the best way to generate a UML diagram from Python source code? is not applicable.
- Tried Pyreverse of Pylint: Graphs are only per-file. Didn't try project/package level.
- Tried Epydoc: Can't run with py3.
- Tried PyUML. Last release in 2009. It's for Eclipse only.
- [ ] Try these
- [ ] gaphor
- [ ] Umbrello (an IDE)
- [ ] PyNSource : Reverse engineer python source code into UML. Generated UML class diagrams can be displayed as ASCII Art or in a more typical graphical form. After a few years in a zombie state, we have just seen a new and improved version this 2019.
- [ ] Epydoc : Generate UML documentation from python code (last release on 2008)
- [ ] Lumpy . Python module that generates UML diagrams (currently object and class diagrams) from a running Python program. It is similar to a graphical debugger in the sense that it generates a visualization of the state of a running program, but it is different from a debugger in the sense that it tries to generate high-level visualizations that are compliant (at least in spirit) with standard UML
- [ ] And others like ObjectDomain (commercial tool with forward and reverse engineering support for Python) and argoUML-python do not even seem to exist anymore.
- [ ] GraphModels (django-command-extensions) creates a UML-like GraphViz dot file for the specified app name. Latest release from 2009.
- [ ] pywebuml uses graphviz to create a UML class diagram representing your python (and also Java and C#) code. Latest release from 2012.
- [ ] uml-to-django automatically generates the Django model and admin interface from a UML class diagram. My own UMLtoDjango service had a very similar tool, focusing on the automatic generation of CRUD interfaces for Django from a simple class diagram.
Online Python Env#
- @2021-12-18
- https://replit.com/
- [Google Colab]
- [Jupyter]
venv(Virtual Env)#
- @2021-12-18
- my
py
is aliased topython3
(some python version) - create a venv
py -m venv [FOLDER_NAME|PATH]
- activate a venv
source [FOLDER_NAME|PATH]/bin/activate
- update python version of venv
py -m venv --upgrade [ENV_DIR]
Python module method override#
- @2021-12-21
- Its possible to override one method of the module. Override module method where from...import is used
- but the overriden method can not be used in pylance typing.
Turn Python module into Python class#
- @2021-12-21
- Programmatically turn module/set of functions into a Python class
- Pylance can not detect the methods with this method.
Python type assertion#
- @2021-12-21
- "non-null assertion" ("!"operator in typescript),
assert x is not None
. - Is there a way to use type assertion as a type hint? #541
Import from other path#
- @2022-01-02
- Use
.
for current folder (Suggest to use on importing all local, non-pip package) and..
for parent folder, and...
for parent parent folder. - See origin
Relative import in Python3#
- @2022-01-03
- When there's relative import, need to run it as module (not as script) with
python3 -m package.module
- Relative imports in Python 3
Path of Project root#
- @2022-01-04
- Used Python - Get path of root project structure, but it's not available for CLI files. (not compatible with
setuptools
because it changes the path of the file.)
CLI with Python#
- @2022-01-04
- Final solution: Typer
- Tried: Click; pyCLI: deprecated in 2016
- To make the CLI with Typer runnable. I used a modified method of this tutorial from T.Stringer but mainly (maybe only) the
setup.py
.
Formatter in VSCode#
- @2022-01-04
- Formatter in VSCode is just VSCode calling the Python formatter like
black
. If the formatter is not installed (in venv), it will not work. - Origin: Formatter black is not working on my VSCode...but why?
Ellipsis object in Python#
- @2022-01-04
- Ellipsis is a special object(singleton) commonly used by slicing, supports no special operations.
- Ellipsis object in Python
- Official Doc
Pylance typing#
- @2022-01-22
- Stub files are in this repo: python/typeshed
- Work: PR#6998 on python/typeshed
- Trace: While doing Selenium, the
selenium.webdriver.chrome.service
is not correctly defined. The Pylint reports an error "No parameter named "service" and I was trying to create an issue in Selenium repo, but the definition there was correct. Then I checked file path and found it is from vscode-pylance, knowing Pylint is based on Pylance. But the official repo microsoft/pylance-release doesn't contain any stub files. Its README file redirects (in first paragraph, though I saw it from the las paragraph) to microsoft/Pyright and then linked to python/typeshed.
Run as module#
- @2022-01-22
- This is to resolvePython error "ImportError: No module named" or No module named "file1.py"; test1 is not a package
- A package has multiple modules What's the difference between a Python module and a Python package?
__main__
is used as a package's main module. What is main.py?- Setup running config with VSCode.
Async Timer#
- @2022-01-23
- tag: unblocking timer, non-blocking timer.
- Objective: something like setTimeout in JS.
- With Async Python relations between run_until_complete and ensure_future
- The
run_until_complete
will block. More detailsWhy do most asyncio examples use loop.run_until_complete()? - Do not abuse
ensure_future
. From asyncio.ensure_future vs. BaseEventLoop.create_task vs. simple coroutine?
- The
- Also possible, but I didn't test: with
threading.Timer
- Problem is non-blocking but I cannot manipulate another object.
- Non-polling/Non-blocking Timer?
- Postpone code for later execution in python (like setTimeout in javascript)
- Python Time Delays
Selenium4 Chrome Profile#
- @2022-01-23
- Didn't find a solution.
- Selenium doesn't have a good API document.
- (Not helpful) How to open a Chrome Profile through Python says to add_argument "user-data-dir", then I have the same problem as Selenium ChromeDriver: unable to set user-data-dir. Followed this How to use Chrome Profile in Selenium Webdriver Python 3 python webdriver_manager chrome custom profile with Upgrade to Selenium 4 but still not working.
Poetry#
- @2022-01-31
- Install:
curl -sSL https://install.python-poetry.org | python3 -
From Poetry Official Doc - Venv in project
poetry config virtualenvs.in-project true
From Poetry Official Doc: venv and Poetry Official Doc: venv in project - @2022-02-01
- Publish:
poetry publish
From Poetry Official Doc: CLI publish, but need to set PyPI account with either (username and password) or (token). The token is only shown once after getting it. - URL: Poetry Official Doc: URLs can be used to publish to PyPI.
- Poetry will add the developing package to the venv. Removing all packages with
pip
will cause an error (cannot use the CLI intool.poetry.scripts
) that I cannot fix, including rebuilding the venv. Work-around is to restart a project withpoetry new
.
Codecs#
- @2022-01-31
- The default binary codes with str/repr is shown in latin. Inspired by Python: Converting from ISO-8859-1/latin1 to UTF-8
- Encoding
base64
can represent all bytes in string exactly,latin
/latin-1
will have some hidden characters (like\x00
and\x010
).
Python Decorator#
- @2022-01-31
- Decorator is like a high-order function. It takes a function as an argument and returns a function. Learned from Manually calling a decorator that takes arguments. Didn't use Python: Decorators
Change suffix with pathlib#
- @2022-01-31
- Use
Path.with_suffix('.SUFFIX')
. This.
is essential. - The
Path.stem() + '.SUFFIX'
is a bad way to do it. - Adding another suffix to a path that already has a suffix with pathlib
- pathlib
PyNaCl#
- @2022-02-01
- PyNaCl is a Python binding for NaCl.
- The NaCl name (Networking and Cryptography library) is interesting. also the
cr.yp.to
domain. box = nacl.secret.SecretBox(key)
uses anonce
which affects encryption. Yet decryption is not affected by thenonce
.
Encoding#
- @2022-02-02
- Python encoding is a so huge library
- Tried to PR on python/typeshed#7118
- Tried to solve this StackOverflowConvert Python Bytes to String Without Encoding
- Tried to escape latin characters with
\x
.
Pylint#
- @2022-02-01
- Use
# type: ignore
- Ignore one single error
# pylint: disable=no-member
. From Is it possible to ignore one single specific line with Pylint?
Remove file#
- @2022-02-01
- With
pathlib
:Path.unlink()
- With
os
:os.remove("demo/test-del.txt")
Enum in Python#
- @2022-02-01
- The
enum.auto()
is actually a number. - Further reading: String-based enum in Python
PyPI#
- @2022-02-02
- The token is only shown once after getting it.
Remove all package#
- @2022-02-02
- Used
pip list --freeze | xargs pip uninstall -y
from What is the easiest way to remove all packages installed by pip? - Additional: remove requirements
pip uninstall -r requirements.txt
Load JSON schema as Class#
- @2022-02-02
- I haven't figured out how to do it.
- Used materials
Python Singleton#
- @2022-02-02
- #TODO: read Creating a singleton in Python
Interesting new grammar#
- @2022-02-03
for ... yield
=>yield from
- package
six
for py2 and py3 compatiblity - py39 doesn't need
abspath(__file__)
, just__file__
. - From asottile/pyupgrade From python-package-template
Python Versioning#
- @2022-02-03
- Use different Python version with virtualenv