Search code examples
pythonclassoopinheritancewalrus-operator

Odd Syntax (Walrus operator in inheritance)


I was looking in python's grammar and was that you could use the walrus operator in inheritance! Not believing it, I tried it out:

class foo: pass
class bar(foobar := foo): 
    def x(self):
        print("it works!")

b = bar()
b.x()

This does not raise any syntax error (python 3.8.2)! What is the use of it, and how does it work?


Solution

  • It's of no use - so don't use it ;-) Arbitrary expressions are allowed there. For example, this is even more useless:

    from random import choice
    
    class C(choice([int, list])):
        pass
    

    Have fun ;-)