• Alex (unregistered)

    Horrific

  • (cs)

    I think the poor sod had a stammer.

    Or it's a zen thing.

    (fist pots!)

  • nobody (unregistered)

    The Ororor! The Ororor!

    Kurtz

  • tuffy (unregistered)

    It looks like someone is trying to re-implement SQL escaping - the sort Python's DBI handles automatically.

  • Will (unregistered)

    For those of us who don't grok Python or PHP...what is this supposed to do?

  • Pythoneer (unregistered)

    That seem fake, or it's written to be bad on purpose, because I've never seen Python code as bas as that. Python code is usually very readable.

  • strcmp (unregistered)

    WTF is this WTF about? Never done printf()-style debugging with easy to find prefixes? In this case the WTF is that the debugging trace is still in the production code.

    The real WTF is the simple/missing input escaping. But supporting regular expressions as well as OR is a good thing. Doing a substring search instead of a prefix search may be iffy on big datasets, because no indexes can be used.

  • diaphanein (unregistered)

    If I had to guess, I'd say it was debugging output statements left in.... "OROROROROROROROR:" would certainly stand out if you were grepping through logs...

  • Brian (unregistered)

    Yeah it's obviously debugging code. I've done it a million times when you can't run a remote debugger to your deployed platform. It should have been code reviewed, but other than that, the WTF is that the poster didn't even grok that it was debugging code.

  • (cs)

    ROROROROROROROROROROR

  • ted (unregistered)

    Orororor. Must be some kind of debug output in a foreign language.

    But seriously, I don't know Python, could anyone convert this to pseudo code? For example, what the hell does "for field in ('value',)" mean?

    Captcha: doom. Yes, we are doomed.

  • J= (unregistered) in reply to Pythoneer

    I agree. This looks intentionally bad.

    Of course, the programmer could have written it that way with the intention of being confusing.

  • Nacho (unregistered) in reply to Alex
    Alex:
    Horrific

    ORORORORORrific

  • (cs)

    Obligatory note that the real WTF is having to go from Python (a nice, neat little language) to PHP (an appalling dump heap overflowing with the most disgraceful assortment of deplorable rubbish imaginable, mangled up in tangled up knots.)

  • python-challenged (unregistered)

    Could someone please provide a synopsis for the python-challenged? Thanks!

  • tuffy (unregistered) in reply to ted
    ted:
    But seriously, I don't know Python, could anyone convert this to pseudo code? For example, what the hell does "for field in ('value',)" mean?
    ('value',) is a list containing only the string 'value'. This loops over that one list item, thus field is 'value'.
  • Charles Duffy (unregistered) in reply to ted
    ted:
    Orororor. Must be some kind of debug output in a foreign language.

    But seriously, I don't know Python, could anyone convert this to pseudo code? For example, what the hell does "for field in ('value',)" mean?

    It's iterating through a one-item list (well, actually a tuple, which is like a list except it's immutable... but that's hardly the point here), assigning each item in that length-1 list to the variable "field".

    In this case, the same effect could be had by saying "field = 'value'".

    Do you have any other specific questions? conds is clearly a list, so conds.append() does the obvious thing; val[3:] retrieves the substring of vals starting after the third character (so he's matching vals[:3] against 'RE:' and then using vals[3:], which is to say everything after that point, if it does in fact match).

    And trying to do SQL quoting yourself is insane and idiotic. In fact, trying to build SQL queries yourself when tools like SQLAlchemy are available is pretty damned stupid too.

    I [heart] Python -- and do think it's genuinely harder to write unreadable Python than most languages -- but this is pretty bad.

  • Jeremy J (unregistered)

    To quote Col. Kurtz, "The horror.. the horror-orororororororororororor".

  • jsled (unregistered) in reply to tuffy

    () is syntax for tuples, not lists (which are bounded by []). They're both iterable, however.

    This isn't WTF python code, it's just WTF code.

  • Weave Jester (unregistered)

    Obfuscated Python is a rare beast, and the number of WTFs in the above code is rather impressive. From the very first line you know you're in for something special:

    for field in ('value',):
    An for loop iteration over a single valued tuple. A cunning way of writing:
    field = 'value'

    Faced with such WTFness in the very first line, one would think that the author couldn't do any better. Instead, we have:

    if self.request().value(field, None):
    Which would be better expressed:
    if field in self.request:

    The rest of the code seems to deal with transforming (badly) a search string of some description into SQL. Unless the inputs have been previously sanitised, the code appears to be vulnerable to SQL injection attacks.

    The "OROROR..." lines are, I suspect, just messy debugging code. Long strings like this are sometimes used so that the programmer can pick them out by eye.

  • (cs) in reply to J=
    J=:
    I agree. This looks intentionally bad.

    Of course, the programmer could have written it that way with the intention of being confusing.

    No quack.

  • (cs)

    I'd say since these "OROR" are printed, they're used as grep-able keywords through logfiles.

    It's nice to have a python code WTF. We are too focussed on looking on language syntaxes as being the real source of WTFs ( indeed, sometimes bad syntax doesn't help, but when it's really too bad it doesn't even survive in the real world. Or is it ? Damn. ). That's really a cultural problem: PHP and VB, for instance, are cursed due to the fact beginners and non-programmers are thrown in the lion cage without any proper knowledge, figuring out that because syntax is easy and straightforward, they don't need any training.

    What we have here is misplaced laziness. Programmer knows about python syntax but didn't mind looking for proper libraries and maintainable algorithm. ( or maybe code is intentionally unreadable )

  • strcmp (unregistered)

    e.g. getting a 404 ( http://worsethanfailure.com/Comments/ArticleFull ) for innocently clicking "[expand full text]" (simple solution: put a "JS is disabled, press your browser's [back] button twice to see the full article" message there)

  • (cs)

    Wow, I didn't know that many Python aristocrats were lurking around here. You can write crappy code in any language (including gasp python), and you can write elegant code in any language (even vb!). Some languages just attract more beginners so the code base as a whole is degraded.

  • python-challenged (unregistered) in reply to strcmp
    strcmp:
    e.g. getting a 404 ( http://worsethanfailure.com/Comments/ArticleFull ) for innocently clicking "[expand full text]" (simple solution: put a "JS is disabled, press your browser's [back] button twice to see the full article" message there)
    Why - oh why - do people build websites that rely on javascript when it can be disabled, and then don't put in checks to at least let the user know what to do because javascript is disabled
  • (cs)

    Silly. ORs are for rowing boats

  • Bavo (unregistered) in reply to python-challenged
    python-challenged:
    strcmp:
    e.g. getting a 404 ( http://worsethanfailure.com/Comments/ArticleFull ) for innocently clicking "[expand full text]" (simple solution: put a "JS is disabled, press your browser's [back] button twice to see the full article" message there)
    Why - oh why - do people build websites that rely on javascript when it can be disabled, and then don't put in checks to at least let the user know what to do because javascript is disabled

    Browsers can be disabled too, we should stop making websites.

  • martinh (unregistered)

    I suspect that much of the badness in this code comes from the fact that it probably devolved from looping through several fields. That is, the initial code was probably something like:

    for field in ('value1', 'value2', 'value2'):

    Eventually the rest of these possible field names dropped out of usage and whoever did it didn't know about block (un)indents and didn't want to have to go through and unindent all the rest of the code. So they just left the loop in there.

    If you look at it in light of that original thought you'll see that despite this definately being a WTF, it actually kind of makes sense for someone who isn't familiar with many aspects of programming, especially in python. Of course, that's really pretty much the root cause of every WTF ever posted here.

  • slinkp (unregistered) in reply to Charles Duffy
    Charles Duffy:
    I [heart] Python -- and *do* think it's genuinely harder to write unreadable Python than most languages -- but this is pretty bad.

    Agreed. Once you remove all the red herrings like the print statements, looping over a sequence of length one, a conditional that's always true, a list of useless mappings which apparently always have only one key and in the code shown always uses the SAME key (but we don't see where the ors list gets created, so there may be some other keys used elsewhere... but even so, a list of tuples is probably a more appropriate data structure), and doing nine things in one line for no good reason ... and get rid of the list comprehension (nothing wrong with them except that a lot of non-python-using readers of this site won't comprehend them, pun intended)... after removing all that, you're still left with some ugly SQL generation code doing escapes by hand.

    Something like (sorry about the extra blank lines, the "code" tag inserts them):

    field = 'value'
    if self.request().value(field, None):
       val = self.request().value(field, '')
       if val.upper()[:3] == 'RE:':
           conds.append("%s ~ '%s'" % (field, val[3:]))
           continue
       lors = val.upper().split(' OR ')
       for wtf in lors:
           wtf = wtf.replace("*","%").replace("?","_").replace("'","\\'")
           wtf  = '%%%s%%' % '%'.join(wtf.split())
           ors.append((field, wtf))
    
    if ors:
        like_expressions = []
        for name, value in ors:
           like_expressions.append("upper(%s) LIKE upper('%s')" 
                                   % (name, value))
        conds.append('(%s)' % ' OR '.join(like_expressions)
    
  • JL (unregistered)

    For the Python-impaired:

    The code apparently converts a field named "value" (probably from a web request) into an SQL condition clause and adds it to a list of SQL search conditions.

    The "for field in ('value',)" statement iterates over a list containing only the string "value"... The author either used or anticipated using more than one field. As it stands, they could have just written "field = 'value'" and left out the loop.

    "self.request().value(field, None)" must retrieve the value of the field from the web request. The "if" statement means that if this field is empty or the empty string (or any other false value), no condition is added to the condition list.

    If the field value starts with "re:" -- like "re:expr" -- the code adds the condition "value ~ 'expr'". I'm guessing this is to directly add an SQL regular expression to the query. No escaping is performed, so this is a potential injection attack route... except that there is a bug later that will cause an exception if anyone uses this feature.

    If the code doesn't start with "re:", it splits the field value up into clauses separated by the word "or". In each clause, "*" is replaced with "%", "?" is replaced with "_", and single quotation marks are escaped with backslashes (backslashes are not escaped: another potential injection attack). Any runs of whitespace are replaced with "%", and "%" is appended to the beginning and end of the clause. The author appends the resulting transformed clause to the SQL condition list as the single element in a dictionary, for no apparent reason.

    Finally, each condition is turned into an SQL clause "upper(value) LIKE 'transformed clause'", concatenated together with "OR" statements, and surrounded with parentheses, ready to be dropped into an SQL WHERE clause. This final concatenation assumes the conditions in the list are single-element dictionaries, not strings like the "re:" code inserts.

    So:

    value = "rabbit?" yields: "(upper(value) LIKE upper('%RABBIT_%'))"

    value = "a or b* or 'z'" yields: "(upper(value) LIKE upper('%A%') OR upper(value) LIKE upper('%B%%') OR upper(value) LIKE upper('%'Z'%'))"

    value = "'))drop table" yields "(upper(value) LIKE upper('%\'))DROP%TABLE%'))". Not a very good example, but I'd guess it's possible to do something nasty in SQL without using whitespace.

    value = "re:test" throws an exception.

  • slinkp (unregistered) in reply to Weave Jester

    [quote user="Weave Jester"]

    if self.request().value(field, None):
    Which would be better expressed:
    if field in self.request:

    Would it? self.request is evidently a callable of some sort, not a mapping or sequence. And whatever it returns is not a builtin python type either, I don't know what kind of object has a value() method.

  • All-seeing Cliche Owl (unregistered)

    ORORORORORORORORORORORLY?

  • blah (unregistered)
    He has been charged with turning a stack of Python code into nice, shiny PHP.

    and here I am doing the opposite thing, the end result probably looks better though.

  • (cs)

    A fine example of ugly Python code. This should serve as proof that the language isn't the issue when it comes to horrororororific code.

    There are often times when I have to open a bunch of programs in batch, and these times are unpredictable, so a scheduled task wouldn't work here. Instead of clicking on each program's shortcut one at a time, I created a Windows Script Host VBScript (gasp Visual Basic!) to do it for me:

    Dim WSH, FSO
    Dim Shortcuts, Shortcut
    
    Set WSH = WScript.CreateObject("WScript.Shell")
    Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
    
    Shortcuts = Array( _
    	"C:\Path\To\Sample\Application 1.lnk", _
    	"C:\Path\To\Sample\Application 2.lnk", _
    	"C:\Path\To\Sample\Application 3.lnk", _
    	"C:\Path\To\Sample\Application 4.lnk" _
    )
    
    For Each Shortcut In Shortcuts
    	If FSO.FileExists(Shortcut) Then
    		WSH.Run("%comspec% /k " & Chr(34) & Chr(34) & Shortcut & Chr(34) & " & exit" & Chr(34))
    		WScript.Sleep(15000)
    	End If
    Next

    I don't claim it's perfect, but it works for me and, IMHO, it's quite readable. Messy code is solely the individual programmer's responsibility. Programming languages are merely tools at the programmer's disposal, and are almost never the cause for the mess.

    If programmers learn good coding techniques, those same techniques can then be applied to any language. Some people get so caught up in the individual language's syntax that they forget the primary purpose of programming, which is not coding, but problem-solving.

    Addendum (2007-02-28 10:47): This five minute window thing is BS. I only wanted to split WSH.Run into two lines so it didn't cause sidescrolling.

    Alex, when are you ditching this hackjob forum software and going with something robust, such as the codebase Slashdot uses?

  • Terrier (unregistered)

    Grokked!

  • Wene Gerchinko (unregistered)

    the real WTF is...

    that the developer can maintain employment while obviously BAKED out of his/her gourd.

  • CynicalTyler (unregistered)
    Bavo:
    Browsers can be disabled too. We should stop building websites.
    Information can be completely ignored, we should stop communicating. Sorry, hate to be hypocritical and all...
  • dolo54 (unregistered)

    I think I know what they are for... Not knowing the language I assume the print command sends the output to a debug window. The original programmer probably has a lot of output going to that debug window, and wanted this output to jump out at him while debugging this function. I actually do something similar, where I will put "|||||||||||||||| someVar = " to the debug window so I can see it right away. I usually delete that line after the function is good however.

  • Micah Cowan (unregistered)
    I'm not one to trust a language that makes such a big deal out of white-space but having a style imposed on developers does have it's benefits.
    I'm having some trouble understanding what you mean by this; what makes you think "making a big deal out of white-space" imposes a style on you? I have never heard of a style (other than "poor") that doesn't require that all code at a given block-level be indented the same, and that nested blocks are indented further. Have you? Python imposes no style other than consistency in indentation, which is one style that every programmer will employ anyway, to preserve his or her own sanity.

    Personally, I think using whitespace as syntax is pure genius (and I'm a C/Perl hacker, myself); the whole reason bracing "styles" exist is that we can never quite figure out what to do with the useless things ourselves (since we, like Python, just follow the indentation).

  • gamedev (unregistered)

    anytime I write ruby or python code it ends up looking like that :(

  • (cs) in reply to Micah Cowan
    Micah Cowan:
    I'm not one to trust a language that makes such a big deal out of white-space but having a style imposed on developers does have it's benefits.
    I'm having some trouble understanding what you mean by this; what makes you think "making a big deal out of white-space" imposes a style on you? I have never heard of a style (other than "poor") that doesn't require that all code at a given block-level be indented the same, and that nested blocks are indented further. Have you? Python imposes no style other than consistency in indentation, which is one style that every programmer will employ anyway, to preserve his or her own sanity.

    Personally, I think using whitespace as syntax is pure genius (and I'm a C/Perl hacker, myself); the whole reason bracing "styles" exist is that we can never quite figure out what to do with the useless things ourselves (since we, like Python, just follow the indentation).

    So, is that indentation using tabs or spaces?

  • Marcin (unregistered) in reply to powerlord
    powerlord:
    Micah Cowan:
    I'm not one to trust a language that makes such a big deal out of white-space but having a style imposed on developers does have it's benefits.
    I'm having some trouble understanding what you mean by this; what makes you think "making a big deal out of white-space" imposes a style on you? I have never heard of a style (other than "poor") that doesn't require that all code at a given block-level be indented the same, and that nested blocks are indented further. Have you? Python imposes no style other than consistency in indentation, which is one style that every programmer will employ anyway, to preserve his or her own sanity.

    Personally, I think using whitespace as syntax is pure genius (and I'm a C/Perl hacker, myself); the whole reason bracing "styles" exist is that we can never quite figure out what to do with the useless things ourselves (since we, like Python, just follow the indentation).

    So, is that indentation using tabs or spaces?

    Can't it be both?

  • Marc (unregistered)

    OLOLOLOLOLOLOLOLOLOL!!!!11111111

    captcha: sanitarium (how appropriate)

  • Cowbert (unregistered) in reply to fennec
    fennec:
    Obligatory note that the real WTF is having to go from Python (a nice, neat little language) to PHP (an appalling dump heap overflowing with the most disgraceful assortment of deplorable rubbish imaginable, mangled up in tangled up knots.)

    I second this statement. Who in their right mind would port code from python to php?

  • rgz (unregistered)

    Oh swell, some body beat me to it, bah I'll post it anyway. I'll do it differently then

    http://rafb.net/p/4ABXgf38.html

    And remember, the f in wtf stands for fuck.

  • (cs) in reply to Micah Cowan
    Micah Cowan:
    I'm not one to trust a language that makes such a big deal out of white-space but having a style imposed on developers does have it's benefits.
    ...Personally, I think using whitespace as syntax is pure genius (and I'm a C/Perl hacker, myself); the whole reason bracing "styles" exist is that we can never quite figure out what to do with the useless things ourselves (since we, like Python, just follow the indentation).

    Apparently you never programmed in Fortran. Everything had to start in column 7. Ridiculous.

    Blocking by whitespace goes slightly past genius into madness, since there's still that question of tabs-vs-spaces that each text editor wants to know about.

  • (cs) in reply to python-challenged
    python-challenged:
    strcmp:
    e.g. getting a 404 ( http://worsethanfailure.com/Comments/ArticleFull ) for innocently clicking "[expand full text]" (simple solution: put a "JS is disabled, press your browser's [back] button twice to see the full article" message there)
    Why - oh why - do people build websites that rely on javascript when it can be disabled, and then don't put in checks to at least let the user know what to do because javascript is disabled

    There are very few reasons scripting should be disabled these days. Maybe he doesn't want readers who have scripting disabled. You still stuck in Web 0.9 or something?

  • Cowbert (unregistered) in reply to cparker
    cparker:

    Addendum (2007-02-28 10:47): This five minute window thing is BS. I only wanted to split WSH.Run into two lines so it didn't cause sidescrolling.

    Alex, when are you ditching this hackjob forum software and going with something robust, such as the codebase Slashdot uses?

    Badly written perl on a mysql backend doesn't count as a megaWTF to you?

  • python-challenged (unregistered) in reply to Bavo
    Bavo:
    python-challenged:
    strcmp:
    e.g. getting a 404 ( http://worsethanfailure.com/Comments/ArticleFull ) for innocently clicking "[expand full text]" (simple solution: put a "JS is disabled, press your browser's [back] button twice to see the full article" message there)
    Why - oh why - do people build websites that rely on javascript when it can be disabled, and then don't put in checks to at least let the user know what to do because javascript is disabled

    Browsers can be disabled too, we should stop making websites.

    Um, all I suggested was that we at least DETECT the problem and tell the user about it (you know, good programming practice), as opposed to just letting it fall through to a 404 error and making the user figure it out.

  • zikkenare (unregistered) in reply to nobody
    nobody:
    The Ororor! The Ororor!

    Kurtz

    LOOOOOOOOOOOOOL

Leave a comment on “The Black Box of Or”

Log In or post as a guest

Replying to comment #:

« Return to Article