title: How to find out the magic number for the .pyc header in Python 3
body: <p>Python bytecode (.pyc) files have a header that starts with a magic number that changes between Python versions. How can I (programmatically) find out that number for the current Python version in order to generate a valid header? I'm currently hard-coding the one for Python 3.7.1, but that means I now depend on a specific Python version.</p>
  
  <p><a href="https://stackoverflow.com/a/8628185/149392">This answer</a> does exactly what I want using <code>py_compile.MAGIC</code>, but that does not seem to exist anymore in Python 3. How can I do the equivalent in Python 3?</p>
  
  <p>Here's an example of what I'm trying to do:</p>
  
  <pre><code>import dis
  import marshal
  
  PYC_HEADER = b'\x42\x0d\x0d\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
  
  def f():
      print('Hello World')
  
  with open('test.pyc', 'wb') as pyc:
      pyc.write(PYC_HEADER)
      marshal.dump(dis.Bytecode(f).codeobj, pyc)
  </code></pre>
  
  <p>This should create a file <code>test.pyc</code>, which can then be run, using the same Python interpreter as the script, and should print "Hello World!". And it does, but only when using Python 3.7. I'm looking for a way that generates the header for whichever version of Python 3 is used to run the script, rather than hard-coding 3.7.</p>
  
  <p>For context:</p>
  
  <p>I'm compiling a simple programming language to different bytecode formats (LLVM, Java bytecode, Web Assembly and now Python bytecode) as part of a planned tutorial series on compiler construction.</p>
  
  <p>I can generate the Python bytecode using <a href="https://github.com/zachariahreed/byteasm" rel="noreferrer">the byteasm library</a>, which gives me a function as a result. But in order to write the contents to a <code>.pyc</code> file, I need a valid header. By hard-coding the header, the code will only work if the people following the tutorial are running the same version of Python 3 as I am (3.7) or they'd have to manually find out the magic number for their version.</p>