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

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
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

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

Related

  • Automating Kubernetes RBAC Sync With LDAP Entitlements Using Python
  • Building AI Agents With Python, LangChain, and GPT APIs
  • Advancing Robot Vision and Control
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques

Trending

  • Altering XML Tag Position Using Mule 4 With Basic Authentication
  • Software Specs 2.0: An Elaborate Example
  • The Rise of Self‐Service Platforms: How Cloud Development Environments Are Reshaping Dev Culture
  • How to Install and Set Up Jenkins With Docker Compose
  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.0K 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.

Related

  • Automating Kubernetes RBAC Sync With LDAP Entitlements Using Python
  • Building AI Agents With Python, LangChain, and GPT APIs
  • Advancing Robot Vision and Control
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques

Partner Resources

×

Comments

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: