SlideShare a Scribd company logo
1 of 36
Download to read offline
Why You Should Use
     super()
 Though It Sucks
       Eunchong YU
    kroisse@gmail.com
유은총

● Developing with Python for Food
● StyleShare     (2011-2012)
● SmartStudy (2012-)
● http://blog.materialistic.kr/
● https://github.com/kroisse
Extend
class A:
    def parts(self):
        return ['plate', 'nail']

class B(A):
    def parts(self):
        # old-way (before Python 2.2)
        base = A.parts(self)
        return base + ['screw']

>>> b = B()
>>> b.parts()
['plate', 'nail', 'screw']
class A(object): # new-style class
    def parts(self):
        return ['plate', 'nail']

class B(A):
    def parts(self):
        base = super(B, self).parts()
        return base + ['screw']

>>> b = B()
>>> b.parts()
['plate', 'nail', 'screw']
super(Class, self)
Old-fashioned way
class B(A):
    def parts(self, lamp):
        base = A.parts(self, lamp)
        return base + [lamp]

class C(B):
    def parts(self, lamp):
        base = B.parts(self, lamp)
        return sorted(base)
Using super() with new-style classes

class B(A):
    def parts(self, lamp):
        base = super(B, self).parts(lamp)
        return base + [lamp]

class C(B):
    def parts(self, lamp):
        base = super(C, self).parts(lamp)
        return sorted(base)
Diamond Problem

                  class D(B, C)




    class B(A)                     class C(A)




                 class A(object)
class A(object):      class B(A):
    def say(self):        def say(self):
        print 'A',            print 'B',
                              A.say(self)

class C(A):           class D(B, C):
    def say(self):        def say(self):
        print 'C',            print 'D',
        A.say(self)           B.say(self)
                              C.say(self)


              >>> D().say()
              D B A C A
MRO
● Method Resolution Order
● linearize class hierarchy
   ○ using C3 algorithm
● only for new-style classes
class D(B, C)




   class B(A)                     class C(A)




                        class A
                       (object)

D.__mro__   ==   (D,   B, C, A, object)
C.__mro__   ==   (C,   A, object)
B.__mro__   ==   (B,   A, object)
A.__mro__   ==   (A,   object)
B                   I

                       A                D



 object                       C         G         H



                       E                F



I.__mro__   ==   (I,   H, D, B, F, G, C, A, E, object)
H.__mro__   ==   (H,   D, B, F, G, C, A, E, object)
D.__mro__   ==   (D,   B, C, A, object)
B.__mro__   ==   (B,   A, object)
F.__mro__   ==   (F,   C, A, E, object)
G.__mro__   ==   (G,   C, A, object)
C.__mro__   ==   (C,   A, object)
A.__mro__   ==   (A,   object)
E.__mro__   ==   (E,   object)
class A(object):           class B(A):
  def say(self):             def say(self):
    print 'A',                 print 'B',
                               super(B, self).say()

class C(A):                class D(B, C):
  def say(self):             def say(self):
    print 'C',                 print 'D',
    super(C, self).say()       super(D, self).say()



    D.__mro__ == (D, B, C, A, object)

    >>> D().say()
    D B C A
super(Class, self)
to find current position   to traverse
            of the MRO     entire MRO
super(Class, self)
● only for new-style classes
● because classic classes don't have MRO
Why You Should Use
     super()
 Though It Sucks
Diamond, Again

                 class D(B, C)




    class B(A)                   class C(A)




                    class A
                   (object)
class A(object):              class C(A):
  def say(self):                def say(self, arg):
    print 'A',                    print 'C(%s)' % arg,
                                  super(C, self).say()

class B(A):                   class D(B, C):
  def say(self):                def say(self, arg):
    print 'B',                    print 'D(%s)' % arg,
    super(B, self).say()          super(D, self).say(arg)


   D.__mro__ == (D, B, C, A, object)
   >>> D().say(1)
   D(1)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "...", line ..., in say
   TypeError: say() takes exactly 1 argument (2 given)
super(Class, self)
● Does not call the superclass
● Call the next method in the MRO
● You can't expect what will be next
Remember #1:
● Don't change the method signature
  OR

● Send all received arguments to super()
class A(object):              class C(A):
  def say(self, arg):           def say(self, arg):
    print 'A',                    print 'C(%s)' % arg,
                                  super(C, self).say(arg)

class B(A):                   class D(B, C):
  def say(self, arg):           def say(self, arg):
    print 'B',                    print 'D(%s)' % arg,
    super(B, self).say(arg)       super(D, self).say(arg)




   >>> D().say(1)
   D(1) B C(1) A
class A(object):
  def say(self, *args, **kwargs):
    print 'A',

class B(A):
  def say(self, *args, **kwargs):
    print 'B',
    super(B, self).say(*args, **kwargs)

class C(A):
  def say(self, arg, *args, **kwargs):
    print 'C(%s)' % arg,
    super(C, self).say(arg, *args, **kwargs)

class D(B, C):
  def say(self, arg, *args, **kwargs):
    print 'D(%s)' % arg,
    super(D, self).say(arg, *args, **kwargs)
Initialize
class A(object):
    def __init__(self):
        print 'A: init'

class B(object):
    def __init__(self):
        print 'B: init'

class C(A, B):
    def __init__(self):
        super(C, self).__init__()

>>> C()
A: init
<__main__.C object at 0x10157f150>
>>> # so where is B???
C.__mro__ == (C, A, B, object)

                   class C(A, B)




 class A(object)                   class B(object)




                      object
C.__mro__ == (C, A, B, object)

                   class C(A, B)




 class A(object)                   class B(object)




                      object
class A(object):
    def __init__(self):
        print 'A: init'
        super(A, self).__init__()

class B(object):
    def __init__(self):
        print 'B: init'
        super(B, self).__init__()

class C(A, B):
    def __init__(self):
        super(C, self).__init__()

>>> C()
A: init
B: init
<__main__.C object at 0x10157f150>
class A(object):
    def __init__(self, *args, **kwargs):
        print 'A: init'
        super(A, self).__init__(*args, **kwargs)

class B(object):
    def __init__(self, *args, **kwargs):
        print 'B: init'
        super(B, self).__init__(*args, **kwargs)

class C(A, B):
    def __init__(self, *args, **kwargs):
        super(C, self).__init__(*args, **kwargs)

>>> C('hello')
A: init
B: init
TypeError: object.__init__() takes no parameters
Remember #2:
● Don't forget super(C, self).__init__()

●   but how about arguments?
super(Me, self).__init__()
           vs.
  Parent.__init__(self)
class A(object):       class C(A):
  def say(self):         def say(self):
    print 'A',             print 'C',
                           super(C, self).say()

class B(A):            class D(B, C):
  def say(self):         def say(self):
    print 'B',             print 'D',
    A.say(self)            super(D, self).say()


   D.__mro__ == (D, B, C, A, object)

   >>> D().say()
   D B A
Remember #3:
● Don't mix both style
● Caution: classic classes (before Python 2.1)
  ○ obsoleted in Python 3.x
  ○ remained in some standard libs of Python 2.x
● Whether using super() or not
  is a method signature.
Plenty of pitfalls in super()
● verbose syntax — fragile on copy & paste :)
● can't use: super(C, self)[0]
● super(C) ≠ super(C, C)
...but we should use super()
● It's a standard.
● Safer to multiple inheritance
● If you mix with classic style,
  everything will be broken.
References:
●   https://fuhm.net/super-harmful/
●   https://groups.google.com/forum/?hl=en&fromgroups=#!topic/comp.lang.
    python/qswq2zIKS7I
●   http://www.python.org/download/releases/2.2.3/descrintro/#cooperation
●   http://docs.python.org/2/reference/datamodel.html#newstyle
●   http://www.python.org/dev/peps/pep-3135/
●   http://freshfoo.com/blog/object__init__takes_no_parameters

More Related Content

What's hot

The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)Eric Torreborre
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverseLuka Jacobowitz
 
λ | Lenses
λ | Lensesλ | Lenses
λ | LensesOpen-IT
 
Optics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeOptics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeIlan Godik
 
Introduction to programming with dependent types in Scala
Introduction to programming with dependent types in ScalaIntroduction to programming with dependent types in Scala
Introduction to programming with dependent types in ScalaDmytro Mitin
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoidsLuka Jacobowitz
 
Writing DSL with Applicative Functors
Writing DSL with Applicative FunctorsWriting DSL with Applicative Functors
Writing DSL with Applicative FunctorsDavid Galichet
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Luka Jacobowitz
 
Your data structures are made of maths!
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!kenbot
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaznkpart
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New GameJohn De Goes
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
Traversals for all ocasions
Traversals for all ocasionsTraversals for all ocasions
Traversals for all ocasionsLuka Jacobowitz
 
Introducing Monads and State Monad at PSUG
Introducing Monads and State Monad at PSUGIntroducing Monads and State Monad at PSUG
Introducing Monads and State Monad at PSUGDavid Galichet
 

What's hot (19)

The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
 
Scalaz
ScalazScalaz
Scalaz
 
Beyond Scala Lens
Beyond Scala LensBeyond Scala Lens
Beyond Scala Lens
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverse
 
λ | Lenses
λ | Lensesλ | Lenses
λ | Lenses
 
Optics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeOptics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the whole
 
Introduction to programming with dependent types in Scala
Introduction to programming with dependent types in ScalaIntroduction to programming with dependent types in Scala
Introduction to programming with dependent types in Scala
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
 
Writing DSL with Applicative Functors
Writing DSL with Applicative FunctorsWriting DSL with Applicative Functors
Writing DSL with Applicative Functors
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020
 
Your data structures are made of maths!
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaz
 
Sigma type
Sigma typeSigma type
Sigma type
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Type classes
Type classesType classes
Type classes
 
Traversals for all ocasions
Traversals for all ocasionsTraversals for all ocasions
Traversals for all ocasions
 
Introducing Monads and State Monad at PSUG
Introducing Monads and State Monad at PSUGIntroducing Monads and State Monad at PSUG
Introducing Monads and State Monad at PSUG
 

Similar to Why you should use super() though it sucks

Advanced python
Advanced pythonAdvanced python
Advanced pythonEU Edge
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonTendayi Mawushe
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1Zaar Hai
 
Pybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonPybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonChristoph Matthies
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scalaakuklev
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfKoteswari Kasireddy
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonPython Ireland
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionNandan Sawant
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesRobert Lujo
 
601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptxsrinivasa gowda
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in PythonDamian T. Gordon
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsP3 InfoTech Solutions Pvt. Ltd.
 

Similar to Why you should use super() though it sucks (20)

Advanced python
Advanced pythonAdvanced python
Advanced python
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
Pybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonPybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in Python
 
Revision1schema C programming
Revision1schema C programmingRevision1schema C programming
Revision1schema C programming
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
 
CSC Millionaire
CSC MillionaireCSC Millionaire
CSC Millionaire
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examples
 
Type hints Python 3
Type hints  Python 3Type hints  Python 3
Type hints Python 3
 
Python lecture 8
Python lecture 8Python lecture 8
Python lecture 8
 
601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx
 
Revision1 C programming
Revision1 C programmingRevision1 C programming
Revision1 C programming
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 
Oops Quiz
Oops QuizOops Quiz
Oops Quiz
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
 

Recently uploaded

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 

Why you should use super() though it sucks

  • 1. Why You Should Use super() Though It Sucks Eunchong YU kroisse@gmail.com
  • 2. 유은총 ● Developing with Python for Food ● StyleShare (2011-2012) ● SmartStudy (2012-) ● http://blog.materialistic.kr/ ● https://github.com/kroisse
  • 4. class A: def parts(self): return ['plate', 'nail'] class B(A): def parts(self): # old-way (before Python 2.2) base = A.parts(self) return base + ['screw'] >>> b = B() >>> b.parts() ['plate', 'nail', 'screw']
  • 5. class A(object): # new-style class def parts(self): return ['plate', 'nail'] class B(A): def parts(self): base = super(B, self).parts() return base + ['screw'] >>> b = B() >>> b.parts() ['plate', 'nail', 'screw']
  • 7. Old-fashioned way class B(A): def parts(self, lamp): base = A.parts(self, lamp) return base + [lamp] class C(B): def parts(self, lamp): base = B.parts(self, lamp) return sorted(base)
  • 8. Using super() with new-style classes class B(A): def parts(self, lamp): base = super(B, self).parts(lamp) return base + [lamp] class C(B): def parts(self, lamp): base = super(C, self).parts(lamp) return sorted(base)
  • 9. Diamond Problem class D(B, C) class B(A) class C(A) class A(object)
  • 10. class A(object): class B(A): def say(self): def say(self): print 'A', print 'B', A.say(self) class C(A): class D(B, C): def say(self): def say(self): print 'C', print 'D', A.say(self) B.say(self) C.say(self) >>> D().say() D B A C A
  • 11. MRO ● Method Resolution Order ● linearize class hierarchy ○ using C3 algorithm ● only for new-style classes
  • 12. class D(B, C) class B(A) class C(A) class A (object) D.__mro__ == (D, B, C, A, object) C.__mro__ == (C, A, object) B.__mro__ == (B, A, object) A.__mro__ == (A, object)
  • 13. B I A D object C G H E F I.__mro__ == (I, H, D, B, F, G, C, A, E, object) H.__mro__ == (H, D, B, F, G, C, A, E, object) D.__mro__ == (D, B, C, A, object) B.__mro__ == (B, A, object) F.__mro__ == (F, C, A, E, object) G.__mro__ == (G, C, A, object) C.__mro__ == (C, A, object) A.__mro__ == (A, object) E.__mro__ == (E, object)
  • 14. class A(object): class B(A): def say(self): def say(self): print 'A', print 'B', super(B, self).say() class C(A): class D(B, C): def say(self): def say(self): print 'C', print 'D', super(C, self).say() super(D, self).say() D.__mro__ == (D, B, C, A, object) >>> D().say() D B C A
  • 15. super(Class, self) to find current position to traverse of the MRO entire MRO
  • 16. super(Class, self) ● only for new-style classes ● because classic classes don't have MRO
  • 17. Why You Should Use super() Though It Sucks
  • 18. Diamond, Again class D(B, C) class B(A) class C(A) class A (object)
  • 19. class A(object): class C(A): def say(self): def say(self, arg): print 'A', print 'C(%s)' % arg, super(C, self).say() class B(A): class D(B, C): def say(self): def say(self, arg): print 'B', print 'D(%s)' % arg, super(B, self).say() super(D, self).say(arg) D.__mro__ == (D, B, C, A, object) >>> D().say(1) D(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "...", line ..., in say TypeError: say() takes exactly 1 argument (2 given)
  • 20. super(Class, self) ● Does not call the superclass ● Call the next method in the MRO ● You can't expect what will be next
  • 21. Remember #1: ● Don't change the method signature OR ● Send all received arguments to super()
  • 22. class A(object): class C(A): def say(self, arg): def say(self, arg): print 'A', print 'C(%s)' % arg, super(C, self).say(arg) class B(A): class D(B, C): def say(self, arg): def say(self, arg): print 'B', print 'D(%s)' % arg, super(B, self).say(arg) super(D, self).say(arg) >>> D().say(1) D(1) B C(1) A
  • 23. class A(object): def say(self, *args, **kwargs): print 'A', class B(A): def say(self, *args, **kwargs): print 'B', super(B, self).say(*args, **kwargs) class C(A): def say(self, arg, *args, **kwargs): print 'C(%s)' % arg, super(C, self).say(arg, *args, **kwargs) class D(B, C): def say(self, arg, *args, **kwargs): print 'D(%s)' % arg, super(D, self).say(arg, *args, **kwargs)
  • 25. class A(object): def __init__(self): print 'A: init' class B(object): def __init__(self): print 'B: init' class C(A, B): def __init__(self): super(C, self).__init__() >>> C() A: init <__main__.C object at 0x10157f150> >>> # so where is B???
  • 26. C.__mro__ == (C, A, B, object) class C(A, B) class A(object) class B(object) object
  • 27. C.__mro__ == (C, A, B, object) class C(A, B) class A(object) class B(object) object
  • 28. class A(object): def __init__(self): print 'A: init' super(A, self).__init__() class B(object): def __init__(self): print 'B: init' super(B, self).__init__() class C(A, B): def __init__(self): super(C, self).__init__() >>> C() A: init B: init <__main__.C object at 0x10157f150>
  • 29. class A(object): def __init__(self, *args, **kwargs): print 'A: init' super(A, self).__init__(*args, **kwargs) class B(object): def __init__(self, *args, **kwargs): print 'B: init' super(B, self).__init__(*args, **kwargs) class C(A, B): def __init__(self, *args, **kwargs): super(C, self).__init__(*args, **kwargs) >>> C('hello') A: init B: init TypeError: object.__init__() takes no parameters
  • 30. Remember #2: ● Don't forget super(C, self).__init__() ● but how about arguments?
  • 31. super(Me, self).__init__() vs. Parent.__init__(self)
  • 32. class A(object): class C(A): def say(self): def say(self): print 'A', print 'C', super(C, self).say() class B(A): class D(B, C): def say(self): def say(self): print 'B', print 'D', A.say(self) super(D, self).say() D.__mro__ == (D, B, C, A, object) >>> D().say() D B A
  • 33. Remember #3: ● Don't mix both style ● Caution: classic classes (before Python 2.1) ○ obsoleted in Python 3.x ○ remained in some standard libs of Python 2.x ● Whether using super() or not is a method signature.
  • 34. Plenty of pitfalls in super() ● verbose syntax — fragile on copy & paste :) ● can't use: super(C, self)[0] ● super(C) ≠ super(C, C)
  • 35. ...but we should use super() ● It's a standard. ● Safer to multiple inheritance ● If you mix with classic style, everything will be broken.
  • 36. References: ● https://fuhm.net/super-harmful/ ● https://groups.google.com/forum/?hl=en&fromgroups=#!topic/comp.lang. python/qswq2zIKS7I ● http://www.python.org/download/releases/2.2.3/descrintro/#cooperation ● http://docs.python.org/2/reference/datamodel.html#newstyle ● http://www.python.org/dev/peps/pep-3135/ ● http://freshfoo.com/blog/object__init__takes_no_parameters