Handy snippets – Python without the .pyc cruft

I maintain a huge workflowy file of snippets and tricks and, I suspect some of them will be handy for others to use too. I’m going to sharing them regularly, when I’m not sure what to write, mainly to keep the habit of blogging, until it comes naturally.

Part of my professional life, involves me writing a fair amount of python code. When you write python, you end up creating lots of files ending with .py, but when you run the code, you end up with compiled python files, sending in pyc.

If you don’t want loads of pyc files crufting up your workspace, and you’re workignon the command line, there’s a handy little environment variable you can set in your shell, to banish those ugly files once and for good. Run this command before working (or better yet, make it run whenever you open a terminal window):

[code lang=”bash”]

export PYTHONDONTWRITEBYTECODE=1

[/code]

See, isn’t that better?

I picked up this gem from the Hitchhiker’s Guide to Python, a free, opinionated book from Kenneth Reitz about good practices with working with Python. Reading it will almost certainly improve your python – I know mine is better as a result of spending some looking over it.


Posted

in

by

Comments

3 responses to “Handy snippets – Python without the .pyc cruft”

  1. archer920gmailcom Avatar

    Thanks for the tip. I can see the value of not having a bunch of pyc files, but doesn’t removing them force Python to generate the p-code each time you run a script?

    1. mrchrisadams Avatar
      mrchrisadams

      This is true – this setting does force Python to recreate the these pyc files each time.

      That said, it’s a pretty fast process, and I haven’t noticed a delay compared with when I did end up littering my projects with them.

      It’s also removed a whole class of bug I’ve encountered before when the pyc files have been left in a project, but the original .py files were deleted. For me, this alone is worth any speed hit the generation may incur.

      1. archer920gmailcom Avatar

        That’s a fair point. Having bugs from old pyc files would drive me crazy also.