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

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 

Recently uploaded (20)

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 

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