DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Giving AI Agents Safe Access to Legacy Systems: Introducing legacy2mcp
  • Adding Graph Retrieval to a RAG Pipeline With Python
  • Building a Product Recommendation Engine With Neo4j — No ML Library Required
  • 6 Techniques To Reduce LLM API Costs With the Python Library

Trending

  • Avoiding AI Debt as a Team
  • Top Gen AI Frameworks for Go in 2026: A Hands-On Comparison
  • Claude Code Superpowers: The 5-Tool Stack That Ends Limits and Context Amnesia
  • Managing Technical Debt in AI-Generated Code

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Nothing is Private: Python Closures (and ctypes)

Nothing is Private: Python Closures (and ctypes)

By 
Michael Foord
·
Jul. 25, 11 · News
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
8.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in
as i'm sure you know python doesn't have a concept of private members. one trick that is sometimes used is to hide an object inside a python closure, and provide a proxy object that only permits limited access to the original object.

here's a simple example of a hide function that takes an object and returns a proxy. the proxy allows you to access any attribute of the original, but not to set or change any attributes.

def hide(obj):
    class proxy(object):
        __slots__ = ()
        def __getattr__(self, name):
            return getattr(obj, name)
    return proxy()

here it is in action:

>>> class foo(object):
...     def __init__(self, a, b):
...         self.a = a
...         self.b = b
...
>>> f = foo(1, 2)
>>> p = hide(f)
>>> p.a, p.b
(1, 2)
>>> p.a = 3
traceback (most recent call last):
  ...
attributeerror: 'proxy' object has no attribute 'a'

after the hide function has returned the proxy object the __getattr__ method is able to access the original object through the closure . this is stored on the __getattr__ method as the func_closure attribute (python 2) or the __closure__ attribute (python 3). this is a "cell object" and you can access the contents of the cell using the cell_contents attribute:

>>> cell_obj = p.__getattr__.func_closure[0]
>>> cell_obj.cell_contents
<__main__.foo object at 0x...>

this makes hide useless for actually preventing access to the original object. anyone who wants access to it can just fish it out of the cell_contents .

what we can't do from pure-python is*set* the contents of the cell, but nothing is really private in python - or at least not in cpython.

there are two python c api functions, pycell_get and pycell_set , that provide access to the contents of closures. from ctypes we can call these functions and both introspect and modify values inside the cell object:

>>> import ctypes
>>> ctypes.pythonapi.pycell_get.restype = ctypes.py_object
>>> py_obj = ctypes.py_object(cell_obj)
>>> f2 = ctypes.pythonapi.pycell_get(py_obj)
>>> f2 is f
true
>>> new_py_obj = ctypes.py_object(foo(5, 6))
>>> ctypes.pythonapi.pycell_set(py_obj, new_py_obj)
0
>>> p.a, p.b
(5, 6)

as you can see, after the call to pycell_set the proxy object is using the new object we put in the closure instead of the original. using ctypes may seem like cheating, but it would only take a trivial amount of c code to do the same.

two notes about this code.

  1. it isn't (of course) portable across different python implementations
  2. don't ever do this, it's for illustration purposes only!


still, an interesting poke around the cpython internals with ctypes. interestingly i have heard of one potential use case for code like this. it is alleged that at some point armin ronacher was using a similar technique in jinja2 for improving tracebacks. (tracebacks from templating languages can be very tricky because the compiled python code usually bears a quite distant relationship to the original text based template.) just because armin does it doesn't mean you can though... wink

Python (language)

Published at DZone with permission of Michael Foord. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Giving AI Agents Safe Access to Legacy Systems: Introducing legacy2mcp
  • Adding Graph Retrieval to a RAG Pipeline With Python
  • Building a Product Recommendation Engine With Neo4j — No ML Library Required
  • 6 Techniques To Reduce LLM API Costs With the Python Library

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook