#isinstance
That case matches a Call object whose func attribute is a Name object whose id is "sorted".

That stores the expression passed to sorted(...) into "iterable".

If you find yourself in code full of isinstance and attribute checks, consider match-case.
November 7, 2026 at 4:27 AM
Python Tip #310 (of 365):

Match objects by their type and attributes with match-case. 🧵

A class pattern checks an object's type (like isinstance does) and the values of its attributes, capturing attributes into variables.

#Python #DailyPythonTip
Appreciating Python's match-case by parsing Python code
Python's match-case blocks are complex structural pattern matching tools that are often more hassle than they're worth. But they're great for parsing abstract syntax trees.
pym.dev
November 7, 2026 at 4:27 AM
Want isinstance() to work with a protocol? Decorate it with @runtime_checkable.

It only checks that the methods exist, not their signatures. For full checks at runtime, the tutorial points to beartype or typeguard.
November 5, 2026 at 5:04 PM
lines=lambda p:[j for j in map(J,open(p,errors='ignore')) if isinstance(j,dict) and j.get('text')] if p.exists() else []
nm=lambda v:v.get('name') if isinstance(v,dict) else v if isinstance(v,str) else None
November 2, 2026 at 7:54 PM
who=lambda sp,N:sp.get('name') or N.get(str(sp.get('id'))) or ('You' if sp.get('source')=='mic' else 'Speaker '+str(sp.get('id')))
clk=lambda ms:' (%02d:%02d)'%(ms//60000,ms//1000%60) if isinstance(ms,int) else ''
November 2, 2026 at 7:54 PM
names=lambda sa,sm:{k:x for d in [(J(sm or 'null') or {}).get('assignments') or {},J(sa or 'null') or {}] for k,a in d.items() if isinstance(a,dict) for x in [next((nm(a.get(s)) for s in ('user','dom','mic','llm') if nm(a.get(s))),None)] if x}
November 2, 2026 at 7:54 PM
Great catch on the PyYAML date parsing quirk. Because datetime date isn't caught by the primitive isinstance checks, falling through to the open {} schema is definitely a leak. Explicitly normalizing those temporal types 1/2
November 1, 2026 at 7:46 PM
(1/x) Class 3 models almost never failed on the primary goal or UI math; they failed discipline gates during self-review:

1. Over-defensive coding (adding ??, .get(), isinstance, try/except pass, or extra optional params that violate Factory's "no silent fallbacks / no dead options" rule).
October 30, 2026 at 12:57 PM
I think it's really neat, actually! It's a much more elegant way to drill down into types than to write a littany of isinstance() checks. especially for complex structures like AST, having a way to say "check that it matches this type" is super handy and I wish more people used it ^^
October 3, 2026 at 8:12 PM
Oh my fucking god: In #Python runtime checking doesn't work with either NewType nor the newly introduced type alias, you cannot use them in match statements or with isinstance 🤦‍♂️
October 3, 2026 at 9:16 AM
Опубликована запись пробного интервью junior Python-разработчика. Разбираем равенство и идентичность объектов, isinstance(), in, сравнения, перебор коллекций и типичные ошибки в интерпретации выражений. https://www.youtube.com/watch?v=vk8TCbp6Vfc
September 18, 2026 at 7:00 AM
Скоро на канале — новое интервью junior Python-разработчика. Будут успехи и ошибки в понимании сравнений, операторов is и in, isinstance(), перебора коллекций и приоритета операций. Сможет ли кандидат объяснить поведение кода? Спонсоры уже сегодня, публичный доступ в пятницу!
September 15, 2026 at 7:00 AM
“That allows for the practice of goose typing, meaning practicing duck typing with the built-in isinstance function.”

Read more 👉 pym.dev/goose-typing/

#Python
Goose typing
In Python you can practice type checking while also practicing duck typing!
pym.dev
September 13, 2026 at 10:47 PM
My safety check was an assert. Five lines made the module refuse to load without it.
`assert isinstance(flag, bool)` reads like a check. Under `python -O` it is not there at all, and nothing at the call site says so. The usual advice is to stop writing safety checks as asserts. There is a better answer: let the module refuse to be imported in the mode where its checks evaporate. if not __debug__: raise RuntimeError("this module's checks are asserts; refusing to run with -O") $ python useguard.py guard loaded, gate(True) = True $ python -O useguard.py; echo $? RuntimeError: this module's checks are asserts; refusing to run with -O 1 Five lines, and the failure moves from the approval to the import. A deployment that will not start is a different kind of problem from a gate that quietly stopped gating. ## What the runtime will and will not tell you Two different questions get confused here, and they have different answers. **What has this image been imported under?** The optimization level is stamped into the bytecode cache filename, so the artifacts accumulate: $ python use.py && python -O use.py && python -OO use.py $ ls __pycache__ m.cpython-314.opt-1.pyc m.cpython-314.opt-2.pyc m.cpython-314.pyc That is real evidence and it survives the process that made it. It is also easy to lose: $ rm -rf __pycache__ && PYTHONDONTWRITEBYTECODE=1 python -O use.py $ ls __pycache__ (no such directory) A read-only image layer does the same thing. So the artifact answers a forensic question, and answers it only sometimes. **What is this process running under right now?** That one is reliable: $ python probe.py sys.flags.optimize = 0 | __debug__ = True $ python -O probe.py sys.flags.optimize = 1 | __debug__ = False question | source | can it be missing? ---|---|--- what has been imported | `__pycache__/*.opt-N.pyc` | yes: `PYTHONDONTWRITEBYTECODE`, or a read-only layer what is running now | `sys.flags.optimize`, `__debug__` | no The guard uses the second one, which is why it works in an image with no `__pycache__` at all. ## Why "just don't use asserts" is the weaker rule It is advice to every future author of every line in the module, and review is what enforces it. The import guard is one line. The interpreter enforces that one, including over asserts nobody has written yet. It also fails in the right direction. Someone deploying with `-O` for speed gets a crash with a sentence explaining the conflict, at startup, in their own terminal. The alternative is that the same person deploys successfully and finds out later, from an action nobody approved. ## What it does not do It does not make asserts a good way to express a safety invariant. If the check matters, `if not isinstance(...): raise` is still better, and the guard is what you put on top of the module while the asserts are still in it. It also stops at the module boundary. A module with the guard is safe under `-O`; a module in the same process without it is not, and nothing coordinates the two. Both of those cost more than five lines. This costs five. _Measured on CPython 3.14.4 (Windows) and cross-checked against 3.14.6 on macOS by @vinhnguyenthanhdn, who pointed out the`__pycache__` artifact in the first place. The three-file listing and the `PYTHONDONTWRITEBYTECODE` result are reproduced from runs on both._
dev.to
September 6, 2026 at 7:16 PM
Python Tip #242 (of 365):

Prefer isinstance over type for type checking. 🧵

Do this:
isinstance(value, int)

Not this:
type(value) == int

Unlike comparing with type(...), using isinstance respects inheritance.

#Python #DailyPythonTip
August 30, 2026 at 6:04 PM
Need to check for multiple types at once? Pass a tuple to isinstance:

>>> isinstance(4.5, (int, float))
True
>>> isinstance("4.5", (int, float))
False
August 30, 2026 at 6:04 PM
I did learn (possibly from you) to prefer `isinstance`. Did not know about this tuple option, though. Nice!
August 30, 2026 at 6:07 PM
A "type(...) == ..." check fails for subclasses:

>>> from collections import Counter
>>> counts = Counter("hello")
>>> isinstance(counts, dict)
True
>>> type(counts) == dict
False

Checking with type means nobody can inherit from your class without breaking your type check.
August 30, 2026 at 6:04 PM
Also note that the ABCs in collections‍.abc check BEHAVIOR, not inheritance so they can be used for "goose typing" (see tip #219).

>>> from collections‍.abc import Iterable
>>> isinstance("hello", Iterable)
True

That's how I'd recommend asking "is this object iterable?"

bsky.app/profile/trey...
August 30, 2026 at 6:04 PM
“But duck typing and the isinstance function are not mutually exclusive.”

Read more 👉 pym.dev/goose-typing/

#Python
Goose typing
In Python you can practice type checking while also practicing duck typing!
pym.dev
August 27, 2026 at 10:43 PM
2/3 — Code (Python 3.11+):

Z={"JPY","KRW","VND","CLP","ISK","UGX","PYG"}

def norm(p):
a=p.get("amount");c=str(p.get("currency","")).upper()
if not isinstance(a,(int,float)):return {"valid":False,"currency":c}
if len(c)!=3 or not c.isalpha():return {"valid":False,"currency":c}
August 27, 2026 at 10:08 AM
August 22, 2026 at 8:50 AM
CVE-2026-76850 - LMDeploy Remote Code Execution via Unsafe Pickle Deserialization in the Disaggregated Serving Peer Connector
CVE ID : CVE-2026-76850

Published : Aug. 19, 2026, 10:17 p.m. | 14 minutes ago

Description : LMDeploy deserializes disaggregated-serving peer mes...
CVE-2026-76850 - LMDeploy Remote Code Execution via Unsafe Pickle Deserialization in the Disaggregated Serving Peer Connector
LMDeploy deserializes disaggregated-serving peer messages with pickle. The handle_zmq_recv coroutine in lmdeploy/pytorch/disagg/conn/engine_conn.py reads peer-to-peer cache-free requests with recv_pyobj(), which deserializes the received bytes with pickle.loads(), and the isinstance check against DistServeCacheFreeRequest runs only after deserialization has already completed. The peer that supplies those bytes is caller-controlled: p2p_connect passes remote_engine_endpoint_info.zmq_address from …
cvefeed.io
August 19, 2026 at 10:56 PM
Alex Martelli coined the term "goose typing" to describe this ability in Python to practice duck typing while also using isinstance and issubclass.

Read more 👉 pym.dev/goose-typing/

#Python
Goose typing
In Python you can practice type checking while also practicing duck typing!
pym.dev
August 15, 2026 at 9:23 PM
A Comprehensive Implementation Guide to ModelScope for Model Search, Inference, Fine-Tuning, Evaluation, and Export

print("\n📊 MODEL EVALUATION\n") eval_results = trainer.evaluate() print(" Evaluation Results:") for key, value in eval_results.items(): if isinstance(value, float): print(f"…
A Comprehensive Implementation Guide to ModelScope for Model Search, Inference, Fine-Tuning, Evaluation, and Export
print("\n📊 MODEL EVALUATION\n") eval_results = trainer.evaluate() print(" Evaluation Results:") for key, value in eval_results.items(): if isinstance(value, float): print(f" {key:<25}: {value:.4f}") from sklearn.metrics import classification_report, confusion_matrix preds_output = trainer.predict(eval_ds) preds = np.argmax(preds_output.predictions, axis=-1) labels = preds_output.label_ids print("\n Classification Report:") print(classification_report(labels, preds, target_names=["NEGATIVE", "POSITIVE"])) cm = confusion_matrix(labels, preds) fig, ax = plt.subplots(figsize=(5, 4)) im = ax.imshow(cm, cmap="Blues") ax.set_xticks(); ax.set_yticks() ax.set_xticklabels(["NEGATIVE", "POSITIVE"]) ax.set_yticklabels(["NEGATIVE", "POSITIVE"]) ax.set_xlabel("Predicted"); ax.set_ylabel("Actual") ax.set_title("Confusion Matrix — Fine-Tuned DistilBERT") for i in range(2): for j in range(2): ax.text(j, i, str(cm), ha="center", va="center", color="white" if cm > cm.max()/2 else "black", fontsize=18) plt.colorbar(im) plt.tight_layout() plt.savefig("confusion_matrix.png", dpi=150) plt.show() print(" ✅ Saved confusion_matrix.png") print("\n── Testing Fine-Tuned Model on New Inputs ──") ft_pipeline = hf_pipeline( "sentiment-analysis", model=trainer.model, tokenizer=tokenizer, device=DEVICE, ) new_reviews = [ "An absolutely breathtaking masterpiece with brilliant performances!", "Waste of two hours.
nexttech-news.com
April 9, 2026 at 12:31 AM