r/badcode • • Jun 27 '20

python overmind (reupload)

Post image
894 Upvotes

106 comments sorted by

234

u/xSlendiX_lol Jun 27 '20

Is rhis even real

28

u/MassiveFajiit Jun 27 '20

No but self is ;)

6

u/[deleted] Jun 27 '20

Happy cake day, fellow stranger

7

u/xSlendiX_lol Jun 27 '20

Thank you kind sir

20

u/Neykuratick Jun 27 '20 edited Jun 27 '20

cakeday.congrats(xSlendiX_lol)

14

u/totallyEl3ktrik Jun 27 '20

xSlendix_lol.congratulate("Happy cake day!", Occasions.CAKE_DAY);

4

u/[deleted] Jun 27 '20

why isn't it a static method for RedditUser? That takes a lot of memory....

8

u/BobbitTheDog Jun 27 '20

If you're passing in the occasion anyway, just resolve the message from a dictionary or use a display decorator and interpolate the occasion

3

u/Igoory Jun 27 '20

Happy cake day!

-8

u/TistedLogic Jun 27 '20

🍰***!!***

1

u/Nguyen1427 Oct 08 '20

Happy cake day, fellow stranger

3

u/JayTurnr Jun 27 '20 edited Jun 28 '20

So I run the original code, side by side with everyone's attempts to cut it down with various types to see what happens, here are my results:

Valuecheckif()def /u/TheFirst1Hunter: return adef /u/TheFirst1Hunter on his second example: if type(a) == type(True): / return a / else: / skip()def /u/satchitchatterji: return a if type(a) is bool else None/u/SleepyHarry checkif = lambda a:a==Truedef /u/greenpepperpasta: return a == Truedef /u/sharkbound: if a: / return a
0False0NoneNoneFalseFalseNone
1True1NoneNoneTrueTrue1
2False2NoneNoneFalseFalse2
'text'False'text'NoneNoneFalseFalse'text'
''False''NoneNoneFalseFalseNone
TrueTrueTrueTrueTrueTrueTrueTrue
FalseFalseFalseFalseFalseFalseFalseNone
NoneFalseNoneNoneNoneFalseFalseNone
json.dumps({1:2})False'{"1": 2}'NoneNoneFalseFalse'{"1": 2}'
json.loads('{"1":2}')False{'1': 2}NoneNoneFalseFalse{'1': 2}
[]False[]NoneNoneFalseFalseNone
[0]False[0]NoneNoneFalseFalse[0]
[1]False[1]NoneNoneFalseFalse[1]
{}False{}NoneNoneFalseFalseNone
{0}False{0}NoneNoneFalseFalse{0}
{1}False{1}NoneNoneFalseFalse{1}
Total Matches1623316162

The only two attempts that work are /u/SleepyHarry and /u/greenpepperpasta. Since declaring lambdas as a variable is not best practices, I'm going to have to say /u/greenpepperpasta has the best solution, but I was curious so I ran both methods through timeit.timeit 3 times when a = 2

/u/SleepyHarry - avg of 0.1180102553529044
/u/greenpepperpasta - avg of 0.11839540865427504

In conclusion, I have too much time on my hands and /u/SleepyHarry's lambda function is mildly faster but /u/greenpepperpasta's function is more pythonic.

2

u/Neykuratick Jun 28 '20

that is astonishing, dude

66

u/tittyfuck_00 Jun 27 '20

def killmePlease()

96

u/sn3kgos Jun 27 '20

This is gold standard Pythonic code /s

33

u/[deleted] Jun 27 '20

It is nice to see properly indented code

5

u/sn3kgos Jun 27 '20

Code like this can still be a mess, indentation be damned lol

3

u/scraper03 Jun 27 '20

I hate python specifically because it looks so messy when there's a lot of it

1

u/scraper03 Jun 27 '20

Ok, maybe don't hate it, but I still can't enjoy reading it. I do hate Java and I can read that just fine. It's just... Java...

51

u/TheFirst1Hunter Jun 27 '20

Dude just return a

20

u/SleepyHarry Jun 27 '20

That's not the same behaviour. a is not guaranteed to be a bool.

18

u/TheFirst1Hunter Jun 27 '20

Then why is he comparing it to a Boolean value

10

u/SleepyHarry Jun 27 '20

Ignoring the third conditional, first they check to see if a is not equal to True, then they check to see if a is not equal to False. Nothing about those two checks needs a to be a boolean, does it?

10

u/TheFirst1Hunter Jun 27 '20

That's a really smart point my friend

But he could do

(Sorry if the syntax is wrong but python is not my main)

If a.type==true.type:

  Return a

Else :

Skip()

7

u/sharkbound Jun 27 '20
isinstance

is used in python for checking if something is a type or subtype, ex:

if isinstance(value, bool)

but its not really needed here as python checks if something is truthy or falsey with the if

if value: ...

and the sorta becomes this when the interpreter runs it:

if bool(value) is True

1

u/TheFirst1Hunter Jun 27 '20

Stupid question

How do you do this code thing in reddit

5

u/sharkbound Jun 27 '20

in the new-style editor you click the ... then click the box with the T in it, (aka the code block button)

in markdown editor you use 4 spaces or wrap the code with ` like this: `code here`

2

u/Lorddragonfang Jun 27 '20

Except in the code above, the skip() conditionals are unreachable; it returns False on any value except True, even non-bools.

2

u/[deleted] Jun 28 '20

That's right, I guess that's why the author didn't waste time implementing skip

1

u/TheFirst1Hunter Jun 28 '20

He could just type pass

1

u/Dehstil Jun 28 '20

If this is a class, skip could do nothing in the base class, but be overridden in the subclass. I doubt that was the author's intention but you never know.

1

u/[deleted] Jun 27 '20

Then just return !!a

1

u/SleepyHarry Jun 28 '20

Nope. That would return True for e.g. 'x', which is not the original functions behaviour.

25

u/78yoni78 Jun 27 '20

Context please, I need to know

108

u/N0Tgod Jun 27 '20

Is that what happens, when JavaScript programmers switch to Python?

-27

u/P4INKill Jun 27 '20

No, probably the opposite.

16

u/Historica97 Jun 27 '20

For the third condition, can a be not True and not False at the same time ?

38

u/feetzissuck Jun 27 '20

Yea, it could be something different than a boolean

23

u/fakehalo Jun 27 '20

Seems like no value of "a" would make it to the third elif though. Any Boolean or non-boolean would match one of the first two conditions wouldn't it? I can't tell if this is making my brain implode this morning.

4

u/SleepyHarry Jun 27 '20

You're correct. a narrowed to True by the second conditional, which is obv != False

11

u/Historica97 Jun 27 '20

Yes, but can you compare a boolean with a non-boolean ?

6

u/S3ZDNUD3S Jun 27 '20

Idk the python standard. I know above 0 is true in c so... that’s why I write my code this way.

2

u/theboxislost Jun 27 '20

Yep. You just get True for any comparison of non-bool != bool. That is, except for numbers. 0 is False and 1 is True.

2

u/BruderKumar Jun 27 '20

Yep. 1 even equals True and 0 equals False.

3

u/[deleted] Jun 28 '20

Your down voters are mistaken, bool is a subclass of int in python, True is 1 False is 0. You can test this in the REPL where True == 1 is True as expected but True == 2 is False. Of course int has a bool method that uses the conventional definition True != 0 so True == bool(2) is True.

1

u/BruderKumar Jun 28 '20

Thanks for clearing that up.

3

u/[deleted] Jun 27 '20 edited Jun 27 '20

No. You cannot get past the first two conditions unless you have a comparison function specifically engineered to do so.

If it was ONLY the third condition then yes:

>>> x = ""
>>> x != True and x != False
True

2

u/SleepyHarry Jun 27 '20

Hadn't considered a custom overload of __ne__, good point.

3

u/[deleted] Jun 27 '20 edited Jun 27 '20

Yep, can do all sorts of nasty stuff with overriding:

class A:
    def __init__(self): self.count = 0
    def __ne__(self, other):
        self.count += 1
        return not self.count <= 2

1

u/AutoModerator Jun 27 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

TheAlbinoShadow, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

0

u/[deleted] Jun 27 '20

[deleted]

1

u/AutoModerator Jun 27 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

theboxislost, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/[deleted] Jun 27 '20

Huh? You just repeated what I said. Because the first two evaluate to True, you can't get to the third.

1

u/theboxislost Jun 27 '20

Ah shit, my bad. I brain farted.

1

u/Kidiri90 Jun 27 '20

It could be anything other than a bool, but Python accounts for that.

2

u/S3ZDNUD3S Jun 27 '20

It could be ‘g’

2

u/Timmy_the_tortoise Jun 27 '20

I believe that would evaluate to True.

2

u/SleepyHarry Jun 27 '20

The string 'g' would not "evaluate" to True. Its truthy, so bool('g') is True holds, but the string itself is not equivalent to the bool.

1

u/Timmy_the_tortoise Jun 27 '20

That’s kinda what I meant, but I may also be getting this confused with the javascript == which would make ‘True’ == True True.

Also C where if ‘g’ would be true.

1

u/theboxislost Jun 27 '20

Yes but comparing to either False or True evaluates to not equal, that is != yields True.

7

u/hotchocolateman6969 Jun 27 '20

This code is basically...

Yeah but no but yeah but no but yeah

4

u/NetherFX Jun 27 '20

Someone refactor this, I wanna see how simple this can get

24

u/satchitchatterji Jun 27 '20
def checkif(a):
    return a if type(a) is bool else None

2

u/SleepyHarry Jun 27 '20

This is wrong. Original function is returns True iff a is True, False otherwise.

5

u/greenpepperpasta Jun 27 '20

actually it returns True iff a == True. For example calling it with a = 1 will return True.

2

u/SleepyHarry Jun 27 '20

Very good point.

1

u/[deleted] Jun 30 '20

Nope. The behavior for any non-bool type for this is entirely different than the original function.

1

u/satchitchatterji Jun 30 '20

Correct, I was mistaken. A better definition would be:

def checkif(a):
    return a==True

1

u/[deleted] Jul 01 '20

Close, but not quite. Your definition would fail to return the expected None result for an instance of this class:

class A:
    def __ne__(self, _): return False

7

u/greenpepperpasta Jun 27 '20
def checkif(a):
    return a == true

This is the simplest way to express it as far as I know. The other responses do not behave the same as the original function.

4

u/SleepyHarry Jun 27 '20

True in python needs a cap T

1

u/[deleted] Jun 30 '20

nah, he just forgot to copy the part above that:

true = True

8

u/giraficorn42 Jun 27 '20

On mobile and I'm not good with python, but I think something like this will do it:

Def checking(a):

If isinstance(a, bool)

Return a

-2

u/LucasDuck13 Jun 27 '20

Don't forget something like

else skip()

5

u/giraficorn42 Jun 27 '20

pass is just a placeholder and takes no action. It is only used when you are required by syntax to have something, but your use case doesn't need to actually do anything. As far as I can tell, the net result of checkif() is that nothing happens if a is not Boolean, so no need for skip(), which only calls pass.

3

u/SleepyHarry Jun 27 '20

checkif=lambda a:a==True

I suppose

1

u/JayTurnr Jun 27 '20

You shouldn't use lambdas to declare functions, you should use them instead of declaring functions

2

u/Lorddragonfang Jun 27 '20

Technically it is the fewest number of characters, though, if we're trying to golf it.

2

u/SleepyHarry Jun 28 '20

I wasn't writing production code. The person I responded to asked for "as simple as it can get" which I chose to interpret as fewest characters / golf.

7

u/Bobsenboii Jun 27 '20

Disgusting.

1

u/georgethescattered Jun 27 '20

What color scheme is that?

2

u/Neykuratick Jun 27 '20

Default material

11

u/hollybollybingbong Jun 27 '20 edited Jun 28 '20

Image Transcription:

python code

def skip(): 
    pass
def checkif(a):
    if a != True: 
        return False 
    elif a != False: 
        return True 
    elif a != True and a != False: 
        if a != True: 
            skip() 
    elif a != False: 
            skip()

a/n - should be fixed now, thanks for letting me know :)!

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

18

u/zeGolem83 Jun 27 '20

Nice, but would be nicer if you used a code block

6

u/hollybollybingbong Jun 27 '20

How can I do that?

9

u/zeGolem83 Jun 27 '20

On desktop you should have the option to insert it in the fancy pants editor bar, on mobile in the official Reddit app you have to do it manually by adding '```' one line before and after the code.

2

u/[deleted] Jun 27 '20

Do not use ```, it is not supported in old reddit.

Instead indent all lines with 4 characters.

3

u/AutoModerator Jun 27 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

TheAlbinoShadow, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

3

u/[deleted] Jun 27 '20

Yeah, what this guy said ^

2

u/SleepyHarry Jun 27 '20

/u/hollybollybingbong peel the source of this comment if you wish

def skip():
    pass

def checkif(a):
    if a != True:
        return False
    elif a != False:
        return True
    elif a != True and a != False:
        if a != True:
            skip()
        elif a != False:
            skip()

4

u/V1tko Jun 27 '20

My eyes are bleeding.

2

u/[deleted] Jun 27 '20

Big brain

2

u/[deleted] Jun 27 '20

Beyond Turing Completeness

1

u/random_guy86 Jun 27 '20

I need to bleach my eyes

1

u/pho_real_guy Jun 27 '20

Negativland’s ‘True False’ https://youtu.be/8FayJrdnZN0

1

u/smolderas Jun 27 '20

Must be a stroke victim.

1

u/Marvin0509 depraved Jun 27 '20

I like this one because it's so utterly stupid that for once I'm not reminded of something I did myself.

1

u/[deleted] Jun 27 '20

how 2 do pthon code computr logic 2 episode

1

u/ZILtoid1991 Jun 27 '20

This is why dynamic type systems are abominations...

1

u/skwrrkk Jun 27 '20

Wew lad

1

u/[deleted] Jun 28 '20

Everyone knows: True, False, FILE_NOT_FOUND

-1

u/nckfrgsn Jun 27 '20

I knew this was going to be bad as soon as I saw italics

-1

u/wsmj5 Jun 27 '20

This is stupid.