[CentralOH] A Python Blog and a Tricky Question

Andrew Kubera andrewkubera at gmail.com
Sat Aug 20 13:35:02 EDT 2016


Hello all, I have two things:

First:
https://pythonconquerstheuniverse.wordpress.com <https://pythonconquerstheuniverse.wordpress.com/>

I stumbled across this blog just now, and I don't think I've been directed there before; with a name
like that I don't think I'd forget it. There seem to be some good gems written, so I thought I'd share.  


Second: (Not for the light of heart 🐍)

I'm looking for a hack to change an immutable variable passed into a function/method, or rather,
replace the value in the calling frame. This would, I guess, be like passing by reference in C++, but
breaking all type safety. Example:

def foo(a, b): 
# *magic happens*
a = 5
x = "hello, friend"
y = 0
foo(x, y)
x == 5 # True!

Of course this isn't an easy thing, it'd probably segfault if you foo(0, 'literal') or foo(None, 'singleton'), but
I'm ok with that.

I'll probably need inspect (get frames) and I'm not afraid of dis!

Extra points if it works on a method. That's right, we're changing self: 

a is None # False
a.make_me_none()
a is None; # TRUE! 😱

Extra points if foo is a generator (that's right, we're using coroutines to `yield from` and asynchronously
be sent something that the caller will become.)

And yes, I know it's a bad idea, and I know the pythonic answer is trivially:

a = a.foo()

or

a = yield from a.foo()

But at this point, I'm curious - everything I've found is people asking if they could with replies of 'no', but I
don't think the people asking were hoping to manipulate bytecode.

At the core, this would allow you to write a statement (assignment) in a place that only allows an expression.
Also, this allows one to write code in such a way that you can return boolean, and change a variable at the
same time.

----- Pre-Send Update -----

Alright, by the time I finished writing that problem out and hitting 'send', I actually found a solution <http://faster-cpython-zh.readthedocs.io/en/latest/mutable.html>; it was much
easier than I thought (hint: sys._getframe()), but I think it could be better.

As an example, I've written __call__ in class X to replace the object calling it with the argument:

>>> a = X()
>>> a(8)
>>> a
8

I'm curious if anyone else finds a clever implementation.

- Andrew Kubera

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/centraloh/attachments/20160820/e9e56f89/attachment.html>


More information about the CentralOH mailing list