惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
MyScale Blog
MyScale Blog
量子位
WordPress大学
WordPress大学
F
Full Disclosure
V
V2EX
美团技术团队
I
InfoQ
GbyAI
GbyAI
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Security Archives - TechRepublic
Security Archives - TechRepublic
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
TaoSecurity Blog
TaoSecurity Blog
大猫的无限游戏
大猫的无限游戏
Project Zero
Project Zero
Spread Privacy
Spread Privacy
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Application and Cybersecurity Blog
Application and Cybersecurity Blog
阮一峰的网络日志
阮一峰的网络日志
The Register - Security
The Register - Security
罗磊的独立博客
博客园 - 叶小钗
H
Hacker News: Front Page
N
News | PayPal Newsroom
宝玉的分享
宝玉的分享
腾讯CDC
The Cloudflare Blog
T
Threat Research - Cisco Blogs
Latest news
Latest news
博客园 - 司徒正美
T
Tailwind CSS Blog
H
Help Net Security
IT之家
IT之家
C
CXSECURITY Database RSS Feed - CXSecurity.com
NISL@THU
NISL@THU
O
OpenAI News
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy International News Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
S
Security @ Cisco Blogs
AWS News Blog
AWS News Blog
T
Tor Project blog
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
T
Threatpost

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Python Object Model: How CPython Represents Everything as an Object
James Lee · 2026-05-17 · via DEV Community

In object-oriented theory, "class" and "object" are two fundamental concepts. In Python, both exist as objects internally. A "class" is an object — called a type object. An instance created from a class is also an object — called an instance object.

Objects can be further classified by their characteristics:

Category Description
Mutable object Can be modified after creation
Immutable object Cannot be modified after creation
Fixed-length object Size is fixed
Variable-length object Size is not fixed

So what does a Python object actually look like internally?

Since Python is implemented in C, a Python object is a C struct that organizes the memory the object occupies. Different types of objects have different data and behaviors — so it's reasonable to guess that different types are represented by different structs. But objects also share common traits — every object needs a reference count for garbage collection. So there must be a common header shared by all object structs.

Let's verify this by reading the source code.


PyObject — The Foundation of All Objects

In CPython, every object is represented by a PyObject struct, and an object reference is a PyObject * pointer. PyObject is defined in Include/object.h:

typedef struct _object {
    _PyObject_HEAD_EXTRA
    Py_ssize_t ob_refcnt;
    struct _typeobject *ob_type;
} PyObject;

Enter fullscreen mode Exit fullscreen mode

Ignoring the _PyObject_HEAD_EXTRA macro for now, the struct contains two fields:

  • ob_refcnt — reference count
  • ob_type — pointer to the type object

Reference count: incremented when something references the object, decremented when the reference is released. When it reaches zero, the object is garbage collected — the simplest GC mechanism.

Type pointer: points to the object's type object, which describes the instance object's data layout and behavior.

_PyObject_HEAD_EXTRA

#ifdef Py_TRACE_REFS
#define _PyObject_HEAD_EXTRA    \
    struct _object *_ob_next;   \
    struct _object *_ob_prev;
#else
#define _PyObject_HEAD_EXTRA
#endif

Enter fullscreen mode Exit fullscreen mode

When Py_TRACE_REFS is defined, this macro expands to two pointers that form a doubly-linked list tracking all live heap objects. This is a debug feature, not enabled in normal builds.

PyVarObject — Variable-Length Objects

For variable-length objects, we need to add a length field on top of PyObject:

typedef struct {
    PyObject ob_base;
    Py_ssize_t ob_size; /* Number of items in variable part */
} PyVarObject;

Enter fullscreen mode Exit fullscreen mode

Fixed-length object (PyObject):        Variable-length object (PyVarObject):
┌──────────────┐                       ┌──────────────┐
│  ob_refcnt   │                       │  ob_refcnt   │
├──────────────┤                       ├──────────────┤
│  ob_type     │                       │  ob_type     │
└──────────────┘                       ├──────────────┤
                                       │  ob_size     │  ← element count
                                       └──────────────┘

Enter fullscreen mode Exit fullscreen mode

Two convenience macros make it easy for other objects to embed these headers:

#define PyObject_HEAD      PyObject ob_base;
#define PyObject_VAR_HEAD  PyVarObject ob_base;

Enter fullscreen mode Exit fullscreen mode


Concrete Object Examples

PyFloatObject — Fixed-Length

A float has a fixed size: just a double on top of the PyObject header:

typedef struct {
    PyObject_HEAD
    double ob_fval;
} PyFloatObject;

Enter fullscreen mode Exit fullscreen mode

PyFloatObject (pi = 3.14):
┌──────────────┐
│  ob_refcnt   │  = 1
├──────────────┤
│  ob_type     │──▶ PyFloat_Type
├──────────────┤
│  ob_fval     │  = 3.14
└──────────────┘

Enter fullscreen mode Exit fullscreen mode

PyListObject — Variable-Length

A list has a variable size — it uses a dynamic array to store element pointers:

typedef struct {
    PyObject_VAR_HEAD
    PyObject **ob_item;
    Py_ssize_t allocated;
} PyListObject;

Enter fullscreen mode Exit fullscreen mode

PyListObject:
┌──────────────┐
│  ob_refcnt   │
├──────────────┤
│  ob_type     │──▶ PyList_Type
├──────────────┤
│  ob_size     │  = current length (e.g. 3)
├──────────────┤
│  ob_item     │──▶ [ *obj0 | *obj1 | *obj2 |  (empty)  ]
├──────────────┤         ↑ pointers to element objects
│  allocated   │  = current capacity (e.g. 4)
└──────────────┘

Enter fullscreen mode Exit fullscreen mode

Three key fields:

  • ob_item — pointer to the dynamic array storing element object pointers
  • allocated — total capacity of the dynamic array
  • ob_size — current number of elements (the list's length)

Object Initialization Macros

// For fixed-length objects: sets ob_refcnt=1, ob_type=type
#define PyObject_HEAD_INIT(type)        \
    { _PyObject_EXTRA_INIT              \
    1, type },

// For variable-length objects: also sets ob_size
#define PyVarObject_HEAD_INIT(type, size)   \
    { PyObject_HEAD_INIT(type) size },

Enter fullscreen mode Exit fullscreen mode

These macros appear frequently throughout CPython's source code.


PyTypeObject — The Foundation of All Types

PyObject gives us the common fields shared by all objects. But two questions remain unanswered:

  1. Different object types need different amounts of memory — where does Python get this information when creating an object?
  2. For a given object, how does Python know what operations it supports?

This meta-information belongs to the object's type, stored in a separate entity. The ob_type pointer in PyObject points right to it. PyTypeObject is defined in Include/object.h:

typedef struct _typeobject {
    PyObject_VAR_HEAD
    const char *tp_name;            /* type name, e.g. "float" */
    Py_ssize_t tp_basicsize;        /* memory size for instances */
    Py_ssize_t tp_itemsize;         /* for variable-length types */

    destructor tp_dealloc;
    printfunc  tp_print;
    getattrfunc tp_getattr;
    setattrfunc tp_setattr;

    // ...
    struct _typeobject *tp_base;    /* base class (inheritance) */
    // ...
} PyTypeObject;

Enter fullscreen mode Exit fullscreen mode

Key fields:

  • tp_name — type name (e.g. "float", "list")
  • tp_basicsize / tp_itemsize — memory layout for creating instances
  • tp_base — pointer to the base class type object
  • tp_dealloc, tp_repr, tp_getattr, etc. — function pointers for supported operations

PyTypeObject is the C-level representation of Python's "class" concept.


Type Object and Instance Object in Memory

>>> float
<class 'float'>
>>> pi = 3.14
>>> e = 2.71
>>> type(pi) is float
True

Enter fullscreen mode Exit fullscreen mode

There is exactly one float type object in the system, holding all meta-information about floats. There can be many float instance objects — pi, e, and countless others.

Memory layout:

┌─────────────────────────────────────────────────────────┐
│                   PyFloat_Type (type object)            │
│  ob_type ──▶ PyType_Type                                │
│  tp_name = "float"                                      │
│  tp_basicsize = sizeof(PyFloatObject)                   │
│  tp_repr = float_repr                                   │
│  ...                                                    │
└─────────────────────────────────────────────────────────┘
      ▲                    ▲
      │ ob_type            │ ob_type
┌─────┴──────┐       ┌─────┴──────┐
│ pi=3.14    │       │ e=2.71     │
│ ob_refcnt=1│       │ ob_refcnt=1│
│ ob_fval=   │       │ ob_fval=   │
│   3.14     │       │   2.71     │
└────────────┘       └────────────┘
(PyFloatObject)      (PyFloatObject)

Enter fullscreen mode Exit fullscreen mode

Note: float, pi, e are just pointers to the actual objects — not the objects themselves.

Since the float type object is globally unique, it's defined as a static global variable in C — PyFloat_Type in Objects/floatobject.c:

PyTypeObject PyFloat_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "float",                                    /* tp_name */
    sizeof(PyFloatObject),                      /* tp_basicsize */
    0,                                          /* tp_itemsize */
    (destructor)float_dealloc,                  /* tp_dealloc */
    // ...
    (reprfunc)float_repr,                       /* tp_repr */
    // ...
};

Enter fullscreen mode Exit fullscreen mode

Line 2 initializes ob_refcnt, ob_type (→ PyType_Type), and ob_size. Line 3 sets tp_name to "float".


PyType_Type — The Type of Types

Every type object is itself an object, so it also has a type. The type of float is type:

>>> float.__class__
<class 'type'>
>>> class Foo(object): pass
>>> Foo.__class__
<class 'type'>

Enter fullscreen mode Exit fullscreen mode

In C, type is represented by PyType_Type, defined in Objects/typeobject.c:

PyTypeObject PyType_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)   // ob_type points to itself!
    "type",                                   /* tp_name */
    sizeof(PyHeapTypeObject),                 /* tp_basicsize */
    sizeof(PyMemberDef),                      /* tp_itemsize */
    (destructor)type_dealloc,                 /* tp_dealloc */
    // ...
    (reprfunc)type_repr,                      /* tp_repr */
    // ...
};

Enter fullscreen mode Exit fullscreen mode

Notice line 2: ob_type points to itselfPyType_Type. This matches Python's behavior:

>>> type.__class__
<class 'type'>
>>> type.__class__ is type
True

Enter fullscreen mode Exit fullscreen mode

PyType_Type is the meta type — the type of all types. It's a crucial object in Python's type system, enabling advanced metaclass-based patterns.


PyBaseObject_Type — The Base of All Types

object is the base class of all types. Its C-level entity is PyBaseObject_Type.

You might expect to find it via PyFloat_Type.tp_base — but that field is left as 0 in the static definition:

0,   /* tp_base */

Enter fullscreen mode Exit fullscreen mode

The missing piece is PyType_Ready, called during interpreter initialization:

int
PyType_Ready(PyTypeObject *type)
{
    // ...
    base = type->tp_base;
    if (base == NULL && type != &PyBaseObject_Type) {
        base = type->tp_base = &PyBaseObject_Type;  // default base = object
        Py_INCREF(base);
    }
    // ...
}

Enter fullscreen mode Exit fullscreen mode

PyType_Ready finishes initializing all type objects — setting tp_base to PyBaseObject_Type for any type that doesn't explicitly specify a base.

PyBaseObject_Type is defined in Objects/typeobject.c:

PyTypeObject PyBaseObject_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "object",                                   /* tp_name */
    sizeof(PyObject),                           /* tp_basicsize */
    0,                                          /* tp_itemsize */
    object_dealloc,                             /* tp_dealloc */
    // ...
    object_repr,                                /* tp_repr */
};

Enter fullscreen mode Exit fullscreen mode

ob_type points to PyType_Type — consistent with Python behavior:

>>> object.__class__
<class 'type'>

Enter fullscreen mode Exit fullscreen mode

And tp_base is not set for PyBaseObject_Type — the inheritance chain must have a terminal node, otherwise attribute lookup would loop forever:

>>> print(object.__base__)
None

Enter fullscreen mode Exit fullscreen mode


The Complete Object Hierarchy

Now we can draw the full picture of CPython's object system:

┌─────────────────────────────────────────────────────────────────┐
│                    Complete Object Hierarchy                    │
│                                                                 │
│   Instances          Type Objects          Meta / Base          │
│                                                                 │
│  ┌────────┐         ┌────────────┐                             │
│  │ pi=3.14│─ob_type▶│ PyFloat_   │                             │
│  └────────┘         │ Type       │─tp_base──┐                  │
│  ┌────────┐         │ "float"    │          │                  │
│  │ e=2.71 │─ob_type▶│            │─ob_type─┐│                  │
│  └────────┘         └────────────┘         ││                  │
│                                            ││                  │
│  ┌────────┐         ┌────────────┐         ││                  │
│  │[1,2,3] │─ob_type▶│ PyList_    │         ││                  │
│  └────────┘         │ Type       │─tp_base─┤│                  │
│                     │ "list"     │─ob_type─┤│                  │
│                     └────────────┘         ││                  │
│                                            ││                  │
│                     ┌────────────┐         ││                  │
│                     │ PyType_    │◀────────┘│                  │
│                     │ Type       │─ob_type─▶(itself)           │
│                     │ "type"     │─tp_base──┤                  │
│                     └────────────┘          │                  │
│                                             ▼                  │
│                     ┌────────────────────────────┐             │
│                     │ PyBaseObject_Type "object" │             │
│                     │ ob_type ──▶ PyType_Type    │             │
│                     │ tp_base = NULL (terminal)  │             │
│                     └────────────────────────────┘             │
└─────────────────────────────────────────────────────────────────┘

Key relationships:
──ob_type──▶  "this object's type is..."
──tp_base──▶  "this type inherits from..."

Enter fullscreen mode Exit fullscreen mode

In summary:

  • All instance objects (pi, e, [1,2,3]) have ob_type → their type object
  • All type objects (float, list) have ob_typePyType_Type (type)
  • All type objects have tp_basePyBaseObject_Type (object) by default
  • PyType_Type has ob_type → itself
  • PyBaseObject_Type has tp_baseNULL (end of inheritance chain)