17
freakko
3y

TIL that Python's "everything is an object" mentality allows you to do

def some_function():
some_function.variable = "abc"

print(some_function.variable)
> abc

Comments
  • 3
    Huh, well I hadn't actually thought of that... Certainly an interesting little bit of trivia xD
  • 3
    @Zaphod65 A student of mine who's never programmed before "discovered" it.
  • 0
    Could maybe see that being useful for tracking the number of times a function is called maybe? Definitely an unexpected behavior.
  • 0
    TIL that Python says "everything is an object."
  • 0
    Also, lets see if it works in JS too. Because, same philosophy.
  • 1
    @Cyanide closest you can get is adding a method to the functions protype and then creating an instance of the function I believe. You can't call a functions methods unless you have an instance of it.
  • 0
    Well, if the indentation is right, you'd have to call some_function() first, for the member to be defined.
  • 1
    @aritzh Darn, you're right. I swear I tested the snippet before ranting it... 🤕
  • 0
    @SOlson thinking about it some more, this is probably how the unittest.mock objects work...
Add Comment