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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • How to Submit a Post to DZone
  • DZone's Article Submission Guidelines
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • Extending Java APIs: Add Missing Features Without the Hassle

Trending

  • How to Submit a Post to DZone
  • DZone's Article Submission Guidelines
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • Extending Java APIs: Add Missing Features Without the Hassle
  1. DZone
  2. Coding
  3. Languages
  4. Nothing is Private: Python Closures (and ctypes)

Nothing is Private: Python Closures (and ctypes)

Michael Foord user avatar by
Michael Foord
·
Jul. 25, 11 · News
Like (0)
Save
Tweet
Share
7.33K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • How to Submit a Post to DZone
  • DZone's Article Submission Guidelines
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • Extending Java APIs: Add Missing Features Without the Hassle

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: