"Python etc" Telegram Channel

Logo of telegram channel pythonetc — Python etc
345
Topics from channel:
Functools
Logo of telegram channel pythonetc — Python etc
Topics from channel:
Functools

"Python etc" Telegram Channel

Channel address: @pythonetc
Categories: Technologies
Language: English
Subscribers: 6,378 (Update date: 2021-10-26)
Description from channel

Regular tips about Python and programming in general
Owner — @pushtaev
The current season is run by @orsinium
Tips are appreciated: https://ko-fi.com/pythonetc / https://sobe.ru/na/pythonetc
© CC BY-SA 4.0 — mention if repost

Comments

You must log in to post a comment.



The latest Messages

2021-09-07 18:00:03 Internally, the module re uses 2 undocumented libraries:

+ sre_parse to parse regular expressions into an abstract syntax tree.
+ sre_compile to compile parsed expression.

The first one can be used to see how a regexp was parsed by Python. There are many better tools and services (like regex101.com) to debug regular expressions but this one is already in the stdlib.

>>> import sre_parse
>>> sre_parse.parse(r'([Pp]ython)\s?etc').dump()
SUBPATTERN 1 0 0
IN
LITERAL 80
LITERAL 112
LITERAL 121
LITERAL 116
LITERAL 104
LITERAL 111
LITERAL 110
MAX_REPEAT 0 1
IN
CATEGORY CATEGORY_SPACE
LITERAL 101
LITERAL 116
LITERAL 99
1.5K views
Open / Comment
2021-08-31 18:00:02 JSON states for "JavaScript Object Notation". It's a subset of JavaScript and representation of values is based on how they are represented in JavaScript:

import json
json.dumps(1) # '1'
json.dumps(1.2) # '1.2'
json.dumps('hi') # '"hi"'
json.dumps({}) # '{}'
json.dumps([]) # '[]'
json.dumps(None) # 'null'
json.dumps(float('inf')) # 'Infinity'
json.dumps(float('nan')) # 'NaN'


The last two examples are valid JavaScript but explicitly forbidden by RFC 4627 "The application/json Media Type for JSON":

> Numeric values that cannot be represented as sequences of digits (such as Infinity and NaN) are not permitted.

And so, the inf / nan values, successfully serialized in Python, can fail deserialization in another language. For example, in Go:

import "encoding/json"

func main() {
var v float64
err := json.Unmarshal(`Infinity`, &v)
println(err)
// Output: invalid character 'I' looking for beginning of value
}


To prevent producing invalid JSON, pass allow_nan=False argument:

json.dumps(float('nan'), allow_nan=False)
# ValueError: Out of range float values are not JSON compliant
2.1K views
Open / Comment
2021-08-26 18:00:16 Python 3.7 introduced Development Mode. The mode can be activated with the -X dev argument and it makes the interpreter produce some helpful warnings. For instance:

+ Unclosed files.
+ Unawaited coroutines.
+ Unknown encoding for str.encode (by default, it is unchecked for empty strings).
+ Memory allocation issues.

$ echo 'open("/dev/null")' > tmp.py
$ python3 -X dev tmp.py
tmp.py:1: ResourceWarning: unclosed file <_io.TextIOWrapper name='/dev/null' mode='r' encoding='UTF-8'>
open("/dev/null")
ResourceWarning: Enable tracemalloc to get the object allocation traceback
2.5K views
Open / Comment
2021-06-30 20:33:43 by @PavelDurmanov
1.5K views
Open / Comment
2021-06-30 20:33:43 Modules have a magic attribute called __path__. Whenever you're doing subpackage imports, __path__ is being searched for
that submodule.

__path__
looks like a list of path strings, e.g ["foo/bar", "/path/to/location"].

So if you do from foo import bar, or import foo.bar, foo's __path__ is being searched for bar. And if found - loaded.

You can play around with __path__ to test it out.

Create simple Python module anywhere on your system:


$ tree
.
└── foo.py

$ cat foo.py
def hello():
return "hello world"

Then, run the interpreter there and do the following:
python
>>> import os
>>> os.__path__ = ["."]
>>> from os.foo import hello
>>> hello()
'hello world'

As you can see, foo is now available under os:
python
>>> os.foo
1.5K views
Open / Comment
2021-06-16 15:33:30 by @PavelDurmanov
2.0K views
Open / Comment
2021-06-16 15:33:29 Have you ever wondered how do relative imports work?


Im pretty sure that you've done something like that at some point:


from . import bar
from .bar import foo



It's using a special magic attribute on the module called __package__.
Lets say you have the following structure:


foo/
__init__.py
bar/
__init__.py
main.py



The value of __package__ for foo/__init__.py is set to "foo", and for foo/bar/__init__.py its "foo.bar".


Note that for main.py __package__ isn't set, that's because main.py is not in a package.


So when you're doing from .bar import buz within foo/__init__.py, it simply appends "bar" to foo/__init__.py's __package__ attribute, esentially it gets translated to from foo.bar import buz.


You can actually hack __package__, e.g:


>>> __package__ = "re"
>>> from . import compile
>>> compile
2.2K viewsedited  
Open / Comment
2021-06-08 21:12:27 This guest post is written by Pythonic Attacks channel.
1.3K views
Open / Comment
2021-06-08 21:12:27 Some operators in Python have special names.
Many Pythonistas know about the notorious "walrus" operator (:=), but there are less famous
ones like the diamond operator (<>) — it's similar to the "not equals" operator but written in SQL style.
The diamond operator was suggested in PEP 401 as one of
the first actions of the new leader of the language Barry Warsaw after Guido went climbing Mount Everest.
Luckily, it was just an April Fool joke and the operator was never really a part of the language.
Yet, it's still available but hidden behind the "import from future" flag.

Usually you compare for non-equality using !=:

>>> "bdfl" != "flufl"
True


But if you enable the "Barry as FLUFL" feature the behavior changes:

>>> from __future__ import barry_as_FLUFL
>>> "bdfl" != "flufl"
File "", line 1
"bdfl" != "flufl"
^
SyntaxError: with Barry as BDFL, use '<>' instead of '!='
>>> "bdfl" <> "flufl"
True


Unfortunately, this easter egg is only working in interactive mode (REPL), but not in usual *.py scripts.

By the way, it's interesting that this feature is marked as becoming mandatory in Python 4.0.
1.4K views
Open / Comment