logoalt Hacker News

hermitdev • yesterday at 8:31 PM • 4 replies • view on HN

> Python is harder to JIT because of the way __dict__ works.

Heh, how about how `__class__` works? Not that I recommend actually doing this, but you can literally change the type of an already instantiated object by reassigning `__class__`:

    >>> class Dog:
    ...     def hi(self):
    ...             print("woof")
    ...
    >>> class Cat:
    ...     def hi(self):
    ...             print("meow")
    ...
    >>> dog = Dog()
    >>> dog.hi()
    woof
    >>> dog.__class__ = Cat
    >>> dog.hi()
    meow
    >>> isinstance(dog, Dog)
    False
    >>> isinstance(dog, Cat)
    True
    >>>

Replies

sakesun • today at 12:25 AM

I've been doing things in Python for over 20 years. Only recently I learn that I can do this.

    >>> Dog.__bases__ = (Cat,)
    >>> isinstance(dog, Dog)
    True
    >>> isinstance(dog, Cat)
    True
    >>>
➕ show 1 reply
esprehn • today at 1:36 AM

That's also possible in JS with __proto__. The prototypes of the classes in the chain can be mutated at runtime too. How to handle these cases is well understood for JITs though and python could do the same.

See also the warning here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

And this related article:

https://mathiasbynens.be/notes/prototypes

➕ show 1 reply
samatman • yesterday at 10:52 PM

Lua has the same property with metatables. LuaJIT, which is very fast, has a solution: if you change a metatable after assigning it, or reassign a metatable, Mike Pall turns his back on you. Your code dies slowly, in the outer darkness of the interpreter loop, never to be JIT’ted upon again.

pjmlp • yesterday at 10:23 PM

Smalltalk, Self and Lisp Machines enter the bar, with live image changes.