5

I want to remove doc strings from a Python program but leave asserts (and __debug__ sections) in. I have been using the -OO flag to generate .pyo files but according to the documentation that removes both asserts and doc strings.

I'm using CPython 2.7.

Clarification: I'm removing the docstrings as a cheap obfuscation method. Management made that decision and I think whether that is a useful thing to do is outside the scope of this question.

Peter Graham
  • 11,323
  • 7
  • 40
  • 42

1 Answers1

3

You can't have half of -O. It removes docstrings and asserts, that's just the way it works. Asserts are usually written to be optional anyway, that is, you can remove them without affecting the behavior of the program.

If I had to remove docstrings and leave all else alone, I would consider writing a tool that opened .pyc files, unmarshaled the contents, modified them (by removing the docstrings), and repacked them as .pyc files. But that would likely be a delicate and fragile tool, if it can even be done that way.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • I've explained why I need to remove docstrings but not asserts in the question. – Peter Graham Jul 16 '12 at 00:22
  • 1
    Surely it would be much easier and quite robust to write a script to scrub the docstrings from the source files before they are compiled. – DaveP Jul 16 '12 at 00:35
  • @PeterGraham: You didn't explain why you want to keep the asserts – and this is the really odd part of your requirements. Asserts are not meant to be needed in production builds. – Sven Marnach Jul 16 '12 at 11:35
  • There are good reasons to keep assertions in production builds, especially of flight code. See: https://stackoverflow.com/a/29741912/1959808 – 0 _ Sep 29 '17 at 08:33