SlideShare a Scribd company logo
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 BORSANIYA
Maulik Borsaniya
 
Lab 4
Lab 4Lab 4
Lab 4
vaminorc
 
Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
Nikunj Parekh
 
Python classes objects
Python classes objectsPython classes objects
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
bpstudy
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
Emertxe Information Technologies Pvt Ltd
 
Doctrator Symfony Live 2011 Paris
Doctrator Symfony Live 2011 ParisDoctrator Symfony Live 2011 Paris
Doctrator Symfony Live 2011 Paris
pablodip
 
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
Mahmoud Samir Fayed
 
Python session 7 by Shan
Python session 7 by ShanPython session 7 by Shan
Python session 7 by Shan
Navaneethan Naveen
 
Ruby objects
Ruby objectsRuby objects
Ruby objects
Reuven Lerner
 
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
Tendayi 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 2021
Jorge 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 202
Mahmoud Samir Fayed
 
Closer look at classes
Closer look at classesCloser look at classes
Closer look at classes
yugandhar vadlamudi
 
Powerful Generic Patterns With Django
Powerful Generic Patterns With DjangoPowerful Generic Patterns With Django
Powerful Generic Patterns With Django
Eric Satterwhite
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in Scala
Jorge Vásquez
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
Aleksander Fabijan
 
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
Mahmoud 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 210
Mahmoud 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 methods
Reuven 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 examples
Robert Lujo
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
Jim 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.ppt
muneshwarbisen1
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
 
OOC in python.ppt
OOC in python.pptOOC in python.ppt
OOC in python.ppt
SarathKumarK16
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.ppt
ssuser419267
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.ppt
UmooraMinhaji
 
Python - Classes and Objects, Inheritance
Python - Classes and Objects, InheritancePython - Classes and Objects, Inheritance
Python - Classes and Objects, Inheritance
erchetanchudasama
 
Implementing and analyzing online experiments
Implementing and analyzing online experimentsImplementing and analyzing online experiments
Implementing and analyzing online experiments
Sean Taylor
 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
Bardia Heydari
 
Advanced python
Advanced pythonAdvanced python
Advanced python
EU Edge
 
Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
ChhaviCoachingCenter
 
S12.s01 - Material TP.pdf
S12.s01 - Material TP.pdfS12.s01 - Material TP.pdf
S12.s01 - Material TP.pdf
julioamericoramirezs
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
OSU Open Source Lab
 
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
Patrick Viafore
 
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
ID Bilişim ve Ticaret Ltd. Şti.
 
科特林λ學
科特林λ學科特林λ學
科特林λ學
彥彬 洪
 
jQuery
jQueryjQuery
jQuery
Jay Poojara
 

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
 
Python - Classes and Objects, Inheritance
Python - Classes and Objects, InheritancePython - Classes and Objects, Inheritance
Python - Classes and Objects, Inheritance
 
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
 

Recently uploaded

Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
Luigi Fugaro
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Peter Caitens
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Flutter vs. React Native: A Detailed Comparison for App Development in 2024
Flutter vs. React Native: A Detailed Comparison for App Development in 2024Flutter vs. React Native: A Detailed Comparison for App Development in 2024
Flutter vs. React Native: A Detailed Comparison for App Development in 2024
dhavalvaghelanectarb
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
widenerjobeyrl638
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Vince Scalabrino
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Computer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdfComputer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdf
chandangoswami40933
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
ervikas4
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 
Cost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App DevelopmentCost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App Development
Softradix Technologies
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
campbellclarkson
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
Streamlining End-to-End Testing Automation
Streamlining End-to-End Testing AutomationStreamlining End-to-End Testing Automation
Streamlining End-to-End Testing Automation
Anand Bagmar
 

Recently uploaded (20)

Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
bgiolcb
bgiolcbbgiolcb
bgiolcb
 
Flutter vs. React Native: A Detailed Comparison for App Development in 2024
Flutter vs. React Native: A Detailed Comparison for App Development in 2024Flutter vs. React Native: A Detailed Comparison for App Development in 2024
Flutter vs. React Native: A Detailed Comparison for App Development in 2024
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Computer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdfComputer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdf
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 
Cost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App DevelopmentCost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App Development
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
Streamlining End-to-End Testing Automation
Streamlining End-to-End Testing AutomationStreamlining End-to-End Testing Automation
Streamlining End-to-End Testing Automation
 

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