Glubs
Glubs

Reputation: 106

Hand write a pyc file?

I am trying to write a compiler that compiles to a pyc file but I am really struggling with what the actual contents of a pyc file is and how it all works. To get more comfortable with the format I wanted to hand write a pyc file but I cannot find any resources on this. I was hoping someone here might have a resource or might be able to tell me how I could go about this.

Thanks for any help!

Upvotes: 1

Views: 287

Answers (1)

Chrispresso
Chrispresso

Reputation: 4070

The short answer is you can't. There isn't a formal spec for how the bytecode must be defined. There is a PEP spec, but nothing for the virtual machine running bytecode (as far as I know). You can either go through code to see how it could be done or you can reverse engineer pieces of it using dis.dis

In [5]: def hello():
   ...:     print("hello")
   ...:

In [6]: dis.dis(hello)
  2           0 LOAD_GLOBAL              0 (print)
              2 LOAD_CONST               1 ('hello')
              4 CALL_FUNCTION            1
              6 POP_TOP
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE

But this type of stuff can change from version to version.

Upvotes: 1

Related Questions