Python's magic numbers

I've been troubleshooting a problem that arose while running a pyc file: RuntimeError: Bad magic number in .pyc file

OK, so how do I find the magic number that is in the myfile.pyc and how do I find the magic number that was expected?

The magic number is the first two bytes of the file. I can get them using xxd:

robert@dante ~/MathScripts
$ xxd myfile.pyc | head -n 1
0000000: 330d 0d0a 33c7 925b 4c29 0000 e300 0000  3...3..[L)......

In other words, the magic number of the python36 version of myfile.pyc is 330d 0d0a.

The python27 version has a different magic number:

$ xxd ../MathScripts_py27/myfile.pyc | head -n 1
0000000: 03f3 0d0a 24d4 f75a 6300 0000 0000 0000  ....$..Zc.......

…namely 03f3 0d0a.

Having got the magic number of my byte-code file, how do I discover the magic number that my current python is expecting? The commands are different in python2 and 3. In python2:

robert@dante ~
$ source activate py27
robert@dante ~
$ python
Python 2.7.15 |Anaconda, Inc.| (default, May  1 2018, 23:32:55)
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import imp
>>> imp.get_magic().encode('hex')

And in python3:

robert@dante ~
$ source activate py36
robert@dante ~
$ python
Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import imp
>>> imp.get_magic().hex()

There's a full list of magic numbers here.

How many times am I going to forget this?

I have been using matplotlib on and off for over 15 years; either using it in its own right (the early days) or as some deeply embedded package whenever I use pandas (last couple years).

So why do I always always forget how to get the damn graphics to display?

Here's an example of plotting from the documentation on pandas.DataFrame.hist:

>>> df = pd.DataFrame({
...     'length': [1.5, 0.5, 1.2, 0.9, 3],
...     'width': [0.7, 0.2, 0.15, 0.2, 1.1]},
...     index= ['pig', 'rabbit', 'duck', 'chicken', 'horse'])
>>> hist = df.hist(bins=3)

When you run that, do you see a nice blue histogram describing the dimensions of farmyard animals? Lucky you. I don't. Because I forgot the magic incantation that needs to go after this.

import matplotlib.pylot as plt

And another thing: this shouldn't work. According to their own documentation, getting matplotlib to operate on OSX—which is what I'm attempting—involves a titanic struggle of framework builds against regular builds, incompatible backends, and bizarre specificity regarding my environment manager (my use of conda apparently means that any perceived irregularities in behaviour are my own damn fault).

OK, I'm done venting. Until the next time I forget the incantation and have to re-learn this.