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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • I Was Tired of Flying Blind With AI Agents, So I Built AgentDog
  • Prompt Injection Is Real, So I Built a Python Firewall for LLM Pipelines
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • From Indicators to Insights: Automating IOC Enrichment Using Python and Threat Feeds

Trending

  • Observability for Agents and Workflows: Tracing Prompts, Tool Calls, and Business Outcomes End-to-End
  • Mastering Fluent Bit: Beginners' Guide for Contributing to Our CNCF Project Website
  • Give Your AI Assistant Long-Term Memory With perag
  • DZone's Article Submission Guidelines
  1. DZone
  2. Coding
  3. Languages
  4. Nothing is Private: Python Closures (and ctypes)

Nothing is Private: Python Closures (and ctypes)

By 
Michael Foord user avatar
Michael Foord
·
Jul. 25, 11 · News
Likes (0)
Comment
Save
Tweet
Share
8.2K Views

Join the DZone community and get the full member experience.

Join For Free
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

  • I Was Tired of Flying Blind With AI Agents, So I Built AgentDog
  • Prompt Injection Is Real, So I Built a Python Firewall for LLM Pipelines
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • From Indicators to Insights: Automating IOC Enrichment Using Python and Threat Feeds

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • 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