SlideShare a Scribd company logo
1 of 33
Mutability
For Good not Evil
Nick Sarbicki
Mutability
For Good not Evil
In nonlocal and global scope
Mutability
For Good(?) not Evil
In nonlocal and global scope
What is mutability?
What is mutability
A mutable object is an object which can be changed “in-place”.
Changing the state of a mutable object updates all variables referencing it.
An immutable object cannot be changed “in-place”.
Changing an immutable object creates a new object for a single variable.
[]
Var A
Var B
Mutable types
[]
Var A
Var B
>>> A.append(1)
Mutable types
[] [1]
Var A
Var B
>>> A.append(1)
Var A
Var B
Mutable types
“a”
Var A
Var B
Immutable types
“a”
Var A
Var B
>>> A += “b”
Immutable types
“a”
“ab”Var A
Var B
>>> A += “b”
Var A
Var B
Immutable types
“a”
What is the issue with mutability?
Mutability is simple on the surface.
However it is a powerful feature of Python that can be misleading.
Without understanding it properly it can lead to strange bugs.
Example - Shared References
Shared references cause problems
Sharing references to objects can cause unexpected results. It’s always best to
avoid sharing references if you don’t need to.
>>> my_list_of_lists = [[]] * 8
>>> my_list_of_lists
[[], [], [], [], [], [], [], []]
>>> my_list_of_lists[0].append(1)
>>> my_list_of_lists
[[1], [1], [1], [1], [1], [1], [1], [1]]
Shared references cause problems
[]
board[0]
>>> board[0].append(1)
board[1]
board[2]
board[3]
board[4]
board[5]
board[6]
board[7]
[1]
board[0]
board[1]
board[2]
board[3]
board[4]
board[5]
board[6]
board[7]
So we just need to watch out for it?
Yes and no.
Understanding and recognising mutability is very important.
Making it obvious is a good way of doing this.
Which is more obvious?
state = []
def append_data(data):
state.append(data)
if __name__ == ‘__main__’:
append_data(1)
state = []
def append_data(data, state):
state.append(data)
return state
if __name__ == ‘__main__’:
state = append_data(1, state)
Which is more obvious?
class StatefulClass:
def __init__(self, data):
self.data = data
self.state = []
def append_data(self):
self.state.append(self.data)
def run(self):
self.append_data()
class StatefulClass:
def __init__(self, data):
self.data = data
self.state = []
def append_data(self, state):
state.append(self.data)
return state
def run(self):
self.state = self.append_data(self.state)
Understand when to use it as well!
Mutable default Arguments
Mutable default arguments are a common GOTCHA in Python as they can change
the expected output of a function in misleading ways.
def func(a, b=[]):
b.append(a)
return b
>>> my_list = func(1)
>>> my_list
[1]
>>> my_new_list = func(1)
>>> my_new_list
[1, 1]
A possible use case for mutable default arguments?
Solving a circular dependency...
# a.py
from b import b1
def a1():
print('hi')
def a2():
b1()
if __name__ == '__main__':
a2()
# b.py
from a import a1
def b1():
a1()
print('there')
if __name__ == '__main__':
b1()
A possible use case for mutable default arguments?
Solving a circular dependency...
# a.py
from b import b1
def a1():
print('hi')
def a2():
b1(a1)
b1()
if __name__ == '__main__':
a2()
# b.py
def b1(func=None, callables=[]):
if func is not None:
callables.append(func)
return
for callable in callables:
callable()
print('there')
if __name__ == '__main__':
b1()
Is this good code?
Is there a good use for mutable default arguments?
Mutable default arguments can solve a lot of problems.
But they are rarely the right way to solve those problems.
Some arguments for memoization and binding in local scope.
Avoid if possible.
So what is a good use of mutability?
Reimplementing the circular dependency
solution
Reimplementing the circular dependency solution
def function_register(func):
callables = [] # <-- Mutable state goes here
class FunctionRegister:
def register_pre_call(self, callable):
callables.append(callable)
return callable
def __call__(self, *args, **kwargs):
for callable in callables:
callable()
return func(*args, **kwargs)
return FunctionRegister()
Reimplementing the circular dependency solution
from function_register import function_register
@function_register
def b():
print('there')
@b.register_pre_call
def a():
print('hi')
if __name__ == '__main__':
b()
Implementing memoization
def memoize(func):
calls = {} # ← Mutable state goes here
def wraps(*args, **kwargs):
key = (tuple(args), tuple(kwargs.items()))
try:
return calls[(tuple(args), tuple(kwargs.items()))]
except KeyError:
ret_val = func(*args, **kwargs)
calls[key] = ret_val
return ret_val
return wraps
In Conclusion
So in conclusion
Avoid shared references.
Avoid default mutable arguments.
But don’t avoid mutability in nonlocal scope.
Keep your code obvious.
Don’t overcomplicate things.
Thanks!
Nick Sarbicki
Nick.Sarbicki.com
(github/gitlab.com)/ndevox
@NDevox

More Related Content

What's hot

Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingJordan Parmer
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Omar Abdelhafith
 
Understanding Javascript Engine to Code Better
Understanding Javascript Engine to Code BetterUnderstanding Javascript Engine to Code Better
Understanding Javascript Engine to Code BetterIhsan Fauzi Rahman
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)Ritika Sharma
 
C++ unit-1-part-11
C++ unit-1-part-11C++ unit-1-part-11
C++ unit-1-part-11Jadavsejal
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: FunctionsAdam Crabtree
 
Primitive Wrappers
Primitive WrappersPrimitive Wrappers
Primitive WrappersBharat17485
 
DUTDIP - Don't Use This Dependency Injection Pattern
DUTDIP - Don't Use This Dependency Injection PatternDUTDIP - Don't Use This Dependency Injection Pattern
DUTDIP - Don't Use This Dependency Injection PatternRushabh Dadbhawala
 
Immutability and pure functions
Immutability and pure functionsImmutability and pure functions
Immutability and pure functionssparkfabrik
 
Handout # 4 functions + scopes
Handout # 4   functions + scopes Handout # 4   functions + scopes
Handout # 4 functions + scopes NUST Stuff
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default argumentsNikhil Pandit
 

What's hot (20)

Generics With Swift
Generics With SwiftGenerics With Swift
Generics With Swift
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
 
Rspec
RspecRspec
Rspec
 
3 Function Overloading
3 Function Overloading3 Function Overloading
3 Function Overloading
 
Understanding Javascript Engine to Code Better
Understanding Javascript Engine to Code BetterUnderstanding Javascript Engine to Code Better
Understanding Javascript Engine to Code Better
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
C++ unit-1-part-11
C++ unit-1-part-11C++ unit-1-part-11
C++ unit-1-part-11
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
Primitive Wrappers
Primitive WrappersPrimitive Wrappers
Primitive Wrappers
 
DUTDIP - Don't Use This Dependency Injection Pattern
DUTDIP - Don't Use This Dependency Injection PatternDUTDIP - Don't Use This Dependency Injection Pattern
DUTDIP - Don't Use This Dependency Injection Pattern
 
Immutability and pure functions
Immutability and pure functionsImmutability and pure functions
Immutability and pure functions
 
Java script
Java scriptJava script
Java script
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Handout # 4 functions + scopes
Handout # 4   functions + scopes Handout # 4   functions + scopes
Handout # 4 functions + scopes
 
Scala functions
Scala functionsScala functions
Scala functions
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 

Similar to Mutability for good not evil

NEW AP Computer Science Exam GridWorld Quick Reference Booklet
NEW AP Computer Science Exam GridWorld Quick Reference BookletNEW AP Computer Science Exam GridWorld Quick Reference Booklet
NEW AP Computer Science Exam GridWorld Quick Reference BookletA Jorge Garcia
 
How Pony ORM translates Python generators to SQL queries
How Pony ORM translates Python generators to SQL queriesHow Pony ORM translates Python generators to SQL queries
How Pony ORM translates Python generators to SQL queriesponyorm
 
Functions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwFunctions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwMayankSinghRawat6
 
Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Gesh Markov
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaEdureka!
 
Frege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMFrege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMDierk König
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data TypesIntroduction to Python Language and Data Types
Introduction to Python Language and Data TypesRavi Shankar
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)Jacek Laskowski
 
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Philip Schwarz
 
HBaseCon 2012 | Storing and Manipulating Graphs in HBase
HBaseCon 2012 | Storing and Manipulating Graphs in HBaseHBaseCon 2012 | Storing and Manipulating Graphs in HBase
HBaseCon 2012 | Storing and Manipulating Graphs in HBaseCloudera, Inc.
 
Storing and manipulating graphs in HBase
Storing and manipulating graphs in HBaseStoring and manipulating graphs in HBase
Storing and manipulating graphs in HBaseDan Lynn
 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional ArchitectureJohn De Goes
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojureJuan-Manuel Gimeno
 

Similar to Mutability for good not evil (17)

Haskell Jumpstart
Haskell JumpstartHaskell Jumpstart
Haskell Jumpstart
 
NEW AP Computer Science Exam GridWorld Quick Reference Booklet
NEW AP Computer Science Exam GridWorld Quick Reference BookletNEW AP Computer Science Exam GridWorld Quick Reference Booklet
NEW AP Computer Science Exam GridWorld Quick Reference Booklet
 
How Pony ORM translates Python generators to SQL queries
How Pony ORM translates Python generators to SQL queriesHow Pony ORM translates Python generators to SQL queries
How Pony ORM translates Python generators to SQL queries
 
Functions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwFunctions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjw
 
Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | Edureka
 
Frege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMFrege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVM
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data TypesIntroduction to Python Language and Data Types
Introduction to Python Language and Data Types
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)
 
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
HBaseCon 2012 | Storing and Manipulating Graphs in HBase
HBaseCon 2012 | Storing and Manipulating Graphs in HBaseHBaseCon 2012 | Storing and Manipulating Graphs in HBase
HBaseCon 2012 | Storing and Manipulating Graphs in HBase
 
Storing and manipulating graphs in HBase
Storing and manipulating graphs in HBaseStoring and manipulating graphs in HBase
Storing and manipulating graphs in HBase
 
Operators & Casts
Operators & CastsOperators & Casts
Operators & Casts
 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional Architecture
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojure
 

Recently uploaded

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
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
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
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
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
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
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 

Recently uploaded (20)

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
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 ...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
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
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
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...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
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...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 

Mutability for good not evil

  • 1. Mutability For Good not Evil Nick Sarbicki
  • 2. Mutability For Good not Evil In nonlocal and global scope
  • 3. Mutability For Good(?) not Evil In nonlocal and global scope
  • 5. What is mutability A mutable object is an object which can be changed “in-place”. Changing the state of a mutable object updates all variables referencing it. An immutable object cannot be changed “in-place”. Changing an immutable object creates a new object for a single variable.
  • 7. [] Var A Var B >>> A.append(1) Mutable types
  • 8. [] [1] Var A Var B >>> A.append(1) Var A Var B Mutable types
  • 10. “a” Var A Var B >>> A += “b” Immutable types
  • 11. “a” “ab”Var A Var B >>> A += “b” Var A Var B Immutable types “a”
  • 12. What is the issue with mutability? Mutability is simple on the surface. However it is a powerful feature of Python that can be misleading. Without understanding it properly it can lead to strange bugs.
  • 13. Example - Shared References
  • 14. Shared references cause problems Sharing references to objects can cause unexpected results. It’s always best to avoid sharing references if you don’t need to. >>> my_list_of_lists = [[]] * 8 >>> my_list_of_lists [[], [], [], [], [], [], [], []] >>> my_list_of_lists[0].append(1) >>> my_list_of_lists [[1], [1], [1], [1], [1], [1], [1], [1]]
  • 15. Shared references cause problems [] board[0] >>> board[0].append(1) board[1] board[2] board[3] board[4] board[5] board[6] board[7] [1] board[0] board[1] board[2] board[3] board[4] board[5] board[6] board[7]
  • 16. So we just need to watch out for it? Yes and no. Understanding and recognising mutability is very important. Making it obvious is a good way of doing this.
  • 17. Which is more obvious? state = [] def append_data(data): state.append(data) if __name__ == ‘__main__’: append_data(1) state = [] def append_data(data, state): state.append(data) return state if __name__ == ‘__main__’: state = append_data(1, state)
  • 18. Which is more obvious? class StatefulClass: def __init__(self, data): self.data = data self.state = [] def append_data(self): self.state.append(self.data) def run(self): self.append_data() class StatefulClass: def __init__(self, data): self.data = data self.state = [] def append_data(self, state): state.append(self.data) return state def run(self): self.state = self.append_data(self.state)
  • 19. Understand when to use it as well!
  • 20. Mutable default Arguments Mutable default arguments are a common GOTCHA in Python as they can change the expected output of a function in misleading ways. def func(a, b=[]): b.append(a) return b >>> my_list = func(1) >>> my_list [1] >>> my_new_list = func(1) >>> my_new_list [1, 1]
  • 21. A possible use case for mutable default arguments? Solving a circular dependency... # a.py from b import b1 def a1(): print('hi') def a2(): b1() if __name__ == '__main__': a2() # b.py from a import a1 def b1(): a1() print('there') if __name__ == '__main__': b1()
  • 22. A possible use case for mutable default arguments? Solving a circular dependency... # a.py from b import b1 def a1(): print('hi') def a2(): b1(a1) b1() if __name__ == '__main__': a2() # b.py def b1(func=None, callables=[]): if func is not None: callables.append(func) return for callable in callables: callable() print('there') if __name__ == '__main__': b1()
  • 23. Is this good code?
  • 24.
  • 25. Is there a good use for mutable default arguments? Mutable default arguments can solve a lot of problems. But they are rarely the right way to solve those problems. Some arguments for memoization and binding in local scope. Avoid if possible.
  • 26. So what is a good use of mutability?
  • 27. Reimplementing the circular dependency solution
  • 28. Reimplementing the circular dependency solution def function_register(func): callables = [] # <-- Mutable state goes here class FunctionRegister: def register_pre_call(self, callable): callables.append(callable) return callable def __call__(self, *args, **kwargs): for callable in callables: callable() return func(*args, **kwargs) return FunctionRegister()
  • 29. Reimplementing the circular dependency solution from function_register import function_register @function_register def b(): print('there') @b.register_pre_call def a(): print('hi') if __name__ == '__main__': b()
  • 30. Implementing memoization def memoize(func): calls = {} # ← Mutable state goes here def wraps(*args, **kwargs): key = (tuple(args), tuple(kwargs.items())) try: return calls[(tuple(args), tuple(kwargs.items()))] except KeyError: ret_val = func(*args, **kwargs) calls[key] = ret_val return ret_val return wraps
  • 32. So in conclusion Avoid shared references. Avoid default mutable arguments. But don’t avoid mutability in nonlocal scope. Keep your code obvious. Don’t overcomplicate things.