SlideShare a Scribd company logo
1 of 19
Download to read offline
USING (AND ABUSING)
PYTHON'S MAGIC METHODS
TO REDUCE GOO CODE
WHO AM I?
• Work at indico (small local
company)
• Previously at Olin College,
Pearson, edX, fetchnotes,
and freelance work
• Semi-retired SO & quora user
• Love playing with the dirty
little secrets of python
PART 1: USING MAGIC
METHODS
YOU CAN’T CONTROL
ACCESS TO ATTRIBUTES IN
PYTHON
class MutableObject(object):
def __init__(self, a):
self.a = a
>>> test = MutableObject("one")
>>> test.a = "two"
NORMAL PYTHON ATTRIBUTES
class MutableObject(object):
def __init__(self, a):
self._a = a
>>> test = MutableObject("one")
>>> test._a = "two" # Feels Wrong
TELLING OTHER USERS NOT TO TOUCH YOUR
ATTRIBUTES
class StubbornObject(object):
def __setattr__(self, key, value):
if hasattr(self, key):
raise ValueError(“Already set in my ways")
else:
object.__setattr__(self, key, value)
>>> test = StubbornObject()
>>> test.a = "one"
>>> test.a = “two” # Now actually errors
ACTUALLY STOPPING PEOPLE FROM TOUCHING
YOUR ATTRIBUTES
PART 2: (AB)USING
MAGIC METHODS
results = my_object.attribute
if not isinstance(results, list):
results = list(results)
# Do Something
EVER WRITTEN CODE LIKE THIS?
class ChangelingObject(object):
list_fields = {"a", "b", "c"}
def __setattr__(self, key, value):
if key in self.list_fields:
value = [value]
object.__setattr__(self, key, value)
>>> test = ChangelingObject()
>>> test.a = 1
>>> print test.a

[1]
NEVER AGAIN WITH SPECIAL PYTHON MAGIC
PART 3: ABUSING MAGIC
METHODS
def add_money(user_id, amount):
session = Session()
user_object =
session.query(User).filter_by(id=user_id).first()
current_value = user_object.balance
try:
user_object.balance = current_value + amount
session.commit()
except ORMException:
session.rollback
class User(object):
# Standard ORM stuff
def __iadd__(self, other):
current = user_object.balance
try:
user_object.balance = current + other
session.commit()
except ORMException:
session.rollback()
def add_money(user_id, amount):
session = Session()
user_object =
session.query(User).filter_by(id=user_id).first()
user_object += amount
SHORT CODE, BUT AT WHAT COST?
PART 4: HERE THERE BE
DRAGONS
class Food(object):
recipes = {
frozenset({"flour", "water"}): "dough",
frozenset({"dough", "yeast"}): "bread",
frozenset({"avocado", "onion"}): "guac",
frozenset({"guac", "bread"}): "tasty snack"
}
def __init__(self, ingredient):
self.name = ingredient
def _mix(self, second):
current_pantry = frozenset({self.name, second.name})
try:
return self.recipes[current_pantry]
except KeyError:
raise ValueError("%s and %s don't mix, trust me" % (self.name,
second.name))
def __add__(self, other):
return Food(self._mix(other))
def __iadd__(self, other):
self.name = self._mix(other)
def __repr__(self):
return self.name
>>> step_one = Food("flour") + Food("water") +
Food("yeast")
>>> step_two = Food("avocado") + Food("onion")
>>> print step_one + step_two



tasty snack
PLEASE NEVER ACTUALLY DO THIS
MAGIC METHODS ARE
EXTREMELY POWERFUL, BUT
REMEMBER:
ALWAYS CODE AS IF THE
PERSON WHO ENDS UP
MAINTAINING YOUR CODE IS
A VIOLENT PSYCHOPATH WHO
KNOWS WHERE YOU LIVE.
— Jeff Atwood

More Related Content

What's hot

PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うbpstudy
 
Doctrator Symfony Live 2011 Paris
Doctrator Symfony Live 2011 ParisDoctrator Symfony Live 2011 Paris
Doctrator Symfony Live 2011 Parispablodip
 
The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189Mahmoud Samir Fayed
 
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
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Jorge Vásquez
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021Jorge Vásquez
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202Mahmoud Samir Fayed
 
Powerful Generic Patterns With Django
Powerful Generic Patterns With DjangoPowerful Generic Patterns With Django
Powerful Generic Patterns With DjangoEric Satterwhite
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in ScalaJorge Vásquez
 
The Ring programming language version 1.4 book - Part 20 of 30
The Ring programming language version 1.4 book - Part 20 of 30The Ring programming language version 1.4 book - Part 20 of 30
The Ring programming language version 1.4 book - Part 20 of 30Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210Mahmoud Samir Fayed
 

What's hot (20)

PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Lab 4
Lab 4Lab 4
Lab 4
 
Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
 
Doctrator Symfony Live 2011 Paris
Doctrator Symfony Live 2011 ParisDoctrator Symfony Live 2011 Paris
Doctrator Symfony Live 2011 Paris
 
The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189
 
Python session 7 by Shan
Python session 7 by ShanPython session 7 by Shan
Python session 7 by Shan
 
Ruby objects
Ruby objectsRuby objects
Ruby objects
 
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
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202
 
Closer look at classes
Closer look at classesCloser look at classes
Closer look at classes
 
Powerful Generic Patterns With Django
Powerful Generic Patterns With DjangoPowerful Generic Patterns With Django
Powerful Generic Patterns With Django
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in Scala
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
 
The Ring programming language version 1.4 book - Part 20 of 30
The Ring programming language version 1.4 book - Part 20 of 30The Ring programming language version 1.4 book - Part 20 of 30
The Ring programming language version 1.4 book - Part 20 of 30
 
The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210
 

Similar to Using and Abusing Magic methods in Python

Python's magic methods
Python's magic methodsPython's magic methods
Python's magic methodsReuven Lerner
 
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
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in PythonDamian T. Gordon
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python ClassJim Yeh
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional ProgrammingFrancesco Bruni
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.pptssuser419267
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.pptUmooraMinhaji
 
Implementing and analyzing online experiments
Implementing and analyzing online experimentsImplementing and analyzing online experiments
Implementing and analyzing online experimentsSean Taylor
 
Advanced python
Advanced pythonAdvanced python
Advanced pythonEU Edge
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingPatrick Viafore
 
科特林λ學
科特林λ學科特林λ學
科特林λ學彥彬 洪
 

Similar to Using and Abusing Magic methods in Python (20)

Python's magic methods
Python's magic methodsPython's magic methods
Python's magic methods
 
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
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
OOC in python.ppt
OOC in python.pptOOC in python.ppt
OOC in python.ppt
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.ppt
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.ppt
 
Implementing and analyzing online experiments
Implementing and analyzing online experimentsImplementing and analyzing online experiments
Implementing and analyzing online experiments
 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
 
Advanced python
Advanced pythonAdvanced python
Advanced python
 
Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
 
S12.s01 - Material TP.pdf
S12.s01 - Material TP.pdfS12.s01 - Material TP.pdf
S12.s01 - Material TP.pdf
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python Typing
 
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
 
科特林λ學
科特林λ學科特林λ學
科特林λ學
 
jQuery
jQueryjQuery
jQuery
 
Scala: A brief tutorial
Scala: A brief tutorialScala: A brief tutorial
Scala: A brief tutorial
 

Recently uploaded

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 

Recently uploaded (20)

Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 

Using and Abusing Magic methods in Python

  • 1. USING (AND ABUSING) PYTHON'S MAGIC METHODS TO REDUCE GOO CODE
  • 2. WHO AM I? • Work at indico (small local company) • Previously at Olin College, Pearson, edX, fetchnotes, and freelance work • Semi-retired SO & quora user • Love playing with the dirty little secrets of python
  • 3. PART 1: USING MAGIC METHODS
  • 4. YOU CAN’T CONTROL ACCESS TO ATTRIBUTES IN PYTHON
  • 5. class MutableObject(object): def __init__(self, a): self.a = a >>> test = MutableObject("one") >>> test.a = "two" NORMAL PYTHON ATTRIBUTES
  • 6. class MutableObject(object): def __init__(self, a): self._a = a >>> test = MutableObject("one") >>> test._a = "two" # Feels Wrong TELLING OTHER USERS NOT TO TOUCH YOUR ATTRIBUTES
  • 7. class StubbornObject(object): def __setattr__(self, key, value): if hasattr(self, key): raise ValueError(“Already set in my ways") else: object.__setattr__(self, key, value) >>> test = StubbornObject() >>> test.a = "one" >>> test.a = “two” # Now actually errors ACTUALLY STOPPING PEOPLE FROM TOUCHING YOUR ATTRIBUTES
  • 9. results = my_object.attribute if not isinstance(results, list): results = list(results) # Do Something EVER WRITTEN CODE LIKE THIS?
  • 10. class ChangelingObject(object): list_fields = {"a", "b", "c"} def __setattr__(self, key, value): if key in self.list_fields: value = [value] object.__setattr__(self, key, value) >>> test = ChangelingObject() >>> test.a = 1 >>> print test.a
 [1] NEVER AGAIN WITH SPECIAL PYTHON MAGIC
  • 11. PART 3: ABUSING MAGIC METHODS
  • 12. def add_money(user_id, amount): session = Session() user_object = session.query(User).filter_by(id=user_id).first() current_value = user_object.balance try: user_object.balance = current_value + amount session.commit() except ORMException: session.rollback
  • 13. class User(object): # Standard ORM stuff def __iadd__(self, other): current = user_object.balance try: user_object.balance = current + other session.commit() except ORMException: session.rollback()
  • 14. def add_money(user_id, amount): session = Session() user_object = session.query(User).filter_by(id=user_id).first() user_object += amount SHORT CODE, BUT AT WHAT COST?
  • 15. PART 4: HERE THERE BE DRAGONS
  • 16. class Food(object): recipes = { frozenset({"flour", "water"}): "dough", frozenset({"dough", "yeast"}): "bread", frozenset({"avocado", "onion"}): "guac", frozenset({"guac", "bread"}): "tasty snack" } def __init__(self, ingredient): self.name = ingredient def _mix(self, second): current_pantry = frozenset({self.name, second.name}) try: return self.recipes[current_pantry] except KeyError: raise ValueError("%s and %s don't mix, trust me" % (self.name, second.name)) def __add__(self, other): return Food(self._mix(other)) def __iadd__(self, other): self.name = self._mix(other) def __repr__(self): return self.name
  • 17. >>> step_one = Food("flour") + Food("water") + Food("yeast") >>> step_two = Food("avocado") + Food("onion") >>> print step_one + step_two
 
 tasty snack PLEASE NEVER ACTUALLY DO THIS
  • 18. MAGIC METHODS ARE EXTREMELY POWERFUL, BUT REMEMBER:
  • 19. ALWAYS CODE AS IF THE PERSON WHO ENDS UP MAINTAINING YOUR CODE IS A VIOLENT PSYCHOPATH WHO KNOWS WHERE YOU LIVE. — Jeff Atwood