Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting shlex in debug mode

Tags:

python

shlex

I wanted to see if shlex was a good choice for something I'm trying to build, so I thought I'd put it in debug mode to play around with it. Only, shlex's constructor has this weird thing it does: it sets self.debug to 0 and then immediately checks if it's true.

…
self.debug = 0
self.token = ''
self.filestack = deque()
self.source = None
if self.debug:
    print 'shlex: reading from %s, line %d' \
          % (self.instream, self.lineno)

I know Python has some powerful metaprogramming features, but I can't figure out how this is intended to work – even if I override the constructor, there's no programmatic way to get between the setting of the value and its use.

Is there supposed to be a way to output the statement in the if self.debug condition (and if so, how?), is it a bug, or is there some third possibility I haven't considered?

like image 223
kojiro Avatar asked May 01 '15 22:05

kojiro


1 Answers

First, I'm pretty sure you've found a bug, and you should go report it. (You should make sure that it's still present in the latest 3.x code, but I just checked, and it is.) I don't see anything unreasonable about shlex objects not allowing you to set debug=1 until after they're initialized… but in that case, they shouldn't be checking self.debug in the initializer, since there's no way it can be set.

But this isn't that hard of a bug to work around. The only thing you lose this way is the first message, which only prints out public attributes you can print yourself. So, for example:

class debugging_shlex(shlex):
    def __init__(self, *args, **kwargs):
        # shlex is an old-style class in 2.7, so no super
        shlex.__init__(self, *args, **kwargs)
        self.debug = 1
        print('shlex: reading from %s, line %d' \
              % (self.instream, self.lineno))

More information for the bug report:

  • The unreachable code was added in this 2000 change, and the only change since then was to fit it to 80 columns.
  • There are no unit tests for the debug argument (not surprising, given that it's barely documented and just says "if you want to use this, read the source"… but you might want to add some anyway).
like image 142
abarnert Avatar answered Oct 04 '22 09:10

abarnert