Python doesn't have a way to clone generators.

At least for a lot of simple cases, however, it's pretty obvious what cloning them should do, and being able to do so would be handy. But for a lot of other cases, it's not at all obvious.

For example, if the generator is using another iterator (one which isn't a generator itself; otherwise the answer would be obvious), like a file, what should happen when you clone it? Does it share the same file iterator? Or get a new iterator that references the same file handle under the covers? Or one that references a dup of the file handle?

So, let's look at what it would take to clone a generator, and what the choices are, and how you'd implement them.

What is a generator?

Under the covers, a generator is just storing the current state of a function—much like a thread does.

In particular, it's just a stack frame, plus a copy of the frame's running flag and code object (so these can be accessed after the generator finishes and the frame goes away). This isn't really specified anywhere in the docs, but the docstring for inspect.isgenerator includes this:
    Generator objects provide these attributes:
        __iter__        defined to support iteration over container
        close           raises a new GeneratorExit exception inside the
                        generator to terminate the iteration
        gi_code         code object
        gi_frame        frame object or possibly None once the generator has
                        been exhausted
        gi_running      set to 1 when generator is executing, 0 otherwise
        next            return the next item from the container
        send            resumes the generator and "sends" a value that becomes
                        the result of the current yield-expression
        throw           used to raise an exception inside the generator

The frame type actually is better documented. Its attributes are listed in a chart in the inspect module docs. But briefly, a frame is a code object; its locals/nonlocals/globals/builtins environment; a next instruction pointer; its exception state; a pointer back up the stack, and some debugging stuff.

So, if you think about it, cloning a generator should just mean:

  • Construct a new frame object with a copy of gi_frame.f_locals, and all the other members exactly the same as gi_frame. (Everything but locals is either immutable, like the code object, or something you'd clearly want to share, like the globals.)
  • Construct a new generator object with that new frame object.
But there are a few problems here:
  • The f_locals is the locals dict—but the actual locals environment, not exposed to Python, is an C array of references. Fortunately, you can call the C functions PyFrame_LocalsToFast and PyFrame_FastToLocals to go back and forth between the two, if you don't mind getting your hands dirty with ctypes.pythonapi.
  • The f_locals includes closure variables—and, obviously, not as closure cells, just as their values. So the FastToLocals shuffle is going to unbind any closure variables and turn them into new locals in the clone. If you want to keep them as closures, you have to go under the covers and deal with the variable arrays directly. Or you can just not allow cloning generators whose functions have any free variables (or cell variables, locals referenced by free variables in functions defined locally within them).
  • The exception state is not actually exposed to Python anywhere.
  • The exception state also includes a borrowed (non-refcounted) reference back to the owning generator, if any. You can't create a borrowed reference from Python, which means that if you clone a generator's frame from Python, you'd be creating a reference cycle and perma-leaking the cloned objects.
And then there's one big giant problem:

Unlike, say, types.CodeType, types.FrameType can't be used to construct a frame object with all its bits. Try it, and you just get "TypeError: cannot create 'frame' instances".

And if you go under the covers to ctypes PyFrame_NewFrame, notice that its first argument is a PyThreadState—a type that isn't exposed to Python at all.

So, this is going to take a lot of C API hacking. You essentially have to replace everything PyFrame_NewFrame does. And a lot of that can't be done from Python. Most obviously, setting up the free and cell variables (but again, you could just punt on that), but many things that could be doable from Python are going to require banging on the C structs because they aren't exposed.


Once you get past that, types.GeneratorType also can't be constructed, but this time, it really is just a simple matter of ctypes; PyGen_New just takes a frame object.

I'm curious enough to go off and try to build a frame constructor callable from Python (punting on the closures) to see if this works; I'll edit this post once I've tried it. But it's not going to be trivial.
5

View comments

It's been more than a decade since Typical Programmer Greg Jorgensen taught the word about Abject-Oriented Programming.

Much of what he said still applies, but other things have changed. Languages in the Abject-Oriented space have been borrowing ideas from another paradigm entirely—and then everyone realized that languages like Python, Ruby, and JavaScript had been doing it for years and just hadn't noticed (because these languages do not require you to declare what you're doing, or even to know what you're doing). Meanwhile, new hybrid languages borrow freely from both paradigms.

This other paradigm—which is actually older, but was largely constrained to university basements until recent years—is called Functional Addiction.
5

I haven't posted anything new in a couple years (partly because I attempted to move to a different blogging platform where I could write everything in markdown instead of HTML but got frustrated—which I may attempt again), but I've had a few private comments and emails on some of the old posts, so I decided to do some followups.

A couple years ago, I wrote a blog post on greenlets, threads, and processes.
6

Looking before you leap

Python is a duck-typed language, and one where you usually trust EAFP ("Easier to Ask Forgiveness than Permission") over LBYL ("Look Before You Leap"). In Java or C#, you need "interfaces" all over the place; you can't pass something to a function unless it's an instance of a type that implements that interface; in Python, as long as your object has the methods and other attributes that the function needs, no matter what type it is, everything is good.
1

Background

Currently, CPython’s internal bytecode format stores instructions with no args as 1 byte, instructions with small args as 3 bytes, and instructions with large args as 6 bytes (actually, a 3-byte EXTENDED_ARG followed by a 3-byte real instruction). While bytecode is implementation-specific, many other implementations (PyPy, MicroPython, …) use CPython’s bytecode format, or variations on it.

Python exposes as much of this as possible to user code.
6

If you want to skip all the tl;dr and cut to the chase, jump to Concrete Proposal.

Why can’t we write list.len()? Dunder methods C++ Python Locals What raises on failure? Method objects What about set and delete? Data members Namespaces Bytecode details Lookup overrides Introspection C API Concrete proposal CPython Analysis

Why can’t we write list.len()?

Python is an OO language. To reverse a list, you call lst.reverse(); to search a list for an element, you call lst.index().
8

Many people, when they first discover the heapq module, have two questions:

Why does it define a bunch of functions instead of a container type? Why don't those functions take a key or reverse parameter, like all the other sorting-related stuff in Python? Why not a type?

At the abstract level, it's often easier to think of heaps as an algorithm rather than a data structure.
1

Currently, in CPython, if you want to process bytecode, either in C or in Python, it’s pretty complicated.

The built-in peephole optimizer has to do extra work fixing up jump targets and the line-number table, and just punts on many cases because they’re too hard to deal with. PEP 511 proposes a mechanism for registering third-party (or possibly stdlib) optimizers, and they’ll all have to do the same kind of work.
3

One common "advanced question" on places like StackOverflow and python-list is "how do I dynamically create a function/method/class/whatever"? The standard answer is: first, some caveats about why you probably don't want to do that, and then an explanation of the various ways to do it when you really do need to.

But really, creating functions, methods, classes, etc. in Python is always already dynamic.

Some cases of "I need a dynamic function" are just "Yeah? And you've already got one".
1

A few years ago, Cesare di Mauro created a project called WPython, a fork of CPython 2.6.4 that “brings many optimizations and refactorings”. The starting point of the project was replacing the bytecode with “wordcode”. However, there were a number of other changes on top of it.

I believe it’s possible that replacing the bytecode with wordcode would be useful on its own.
1

Many languages have a for-each loop. In some, like Python, it’s the only kind of for loop:

for i in range(10): print(i) In most languages, the loop variable is only in scope within the code controlled by the for loop,[1] except in languages that don’t have granular scopes at all, like Python.[2]

So, is that i a variable that gets updated each time through the loop or is it a new constant that gets defined each time through the loop?

Almost every language treats it as a reused variable.
4
Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.