SlideShare una empresa de Scribd logo
1 de 35
Descargar para leer sin conexión
Idiomatic Python

                                        P.C. Shyamshankar

                                          PyCon India 2009


                                       September 25, 2009




P.C. Shyamshankar (PyCon India 2009)        Idiomatic Python   September 25, 2009   1 / 35
Outline



 1   Introduction


 2   Idioms
        Accumulation
        Forgiveness
        Laziness
        Comprehension
        Context
        Odds and Ends




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   2 / 35
The Zen of Python, by Tim Peters

        Beautiful is better than ugly.
        Explicit is better than implicit.
        Simple is better than complex.
        Complex is better than complicated.
        Flat is better than nested.
        Sparse is better than dense.
        Readability counts.
        Special cases aren’t special enough to break the rules.
        Although practicality beats purity.
        Errors should never pass silently.
        Unless explicitly silenced.
        In the face of ambiguity, refuse the temptation to guess.
        There should be one, and preferably only one, obvious way to do it.
        Although that way may not be obvious at first unless you’re Dutch.
        Now is better than never.
        Although never is often better than right now.
        If the implementation is hard to explain, it’s a bad idea.
        If the implementation is easy to explain, it may be a good idea.
        Namespaces are one honking great idea – let’s do more of those!




P.C. Shyamshankar (PyCon India 2009)     Idiomatic Python              September 25, 2009   3 / 35
Idioms




        An Unwritten Rule
        A common use-case.
        Usually to make the code better in some way:
                Readability
                Speed
                Resource Usage




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   4 / 35
Outline



 1   Introduction


 2   Idioms
        Accumulation
        Forgiveness
        Laziness
        Comprehension
        Context
        Odds and Ends




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   5 / 35
Outline



 1   Introduction


 2   Idioms
        Accumulation
        Forgiveness
        Laziness
        Comprehension
        Context
        Odds and Ends




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   6 / 35
Putting strings together.




        Strings are immutable
        String addition creates copies.




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   7 / 35
Join, Don’t Add.




        s = ’’
        for i in list_of_strings :
            s += i
        s = ’’.join(list_of_strings)




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   8 / 35
That’s just what everyone says.




        String addition isn’t evil, just asymptotically slow.




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python         September 25, 2009   9 / 35
Outline



 1   Introduction


 2   Idioms
        Accumulation
        Forgiveness
        Laziness
        Comprehension
        Context
        Odds and Ends




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   10 / 35
EAFP




        It’s Easier to Ask Forgiveness than Permission.
        Asking permission is to LBYL
        But it depends on the context.




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   11 / 35
A Story of Keys in a Dict




        If the key is in the dict, increment its value.
        If not, set its value to 1.




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   12 / 35
Asking for Permission




 if key in my_dict :
     my_dict[key] += 1
 else :
     my_dict[key] == 1




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   13 / 35
Asking for Forgiveness




 try :
     my_dict[key] += 1
 except KeyError :
     my_dict[key] = 1




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   14 / 35
Choosing the right time




        Use the first approach, if you’re more likely to succeed.
        Use the second if you’re more likely to fail.




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python     September 25, 2009   15 / 35
So many choices!




        my dict.get(key, 0) += 1
        my dict.setdefault(key, []).append(value)
        my dict = collections.defaultdict(int)
        my dict = collections.Counter()




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   16 / 35
Outline



 1   Introduction


 2   Idioms
        Accumulation
        Forgiveness
        Laziness
        Comprehension
        Context
        Odds and Ends




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   17 / 35
Be Lazy!




 Compute only what you need to compute. It saves time.
 Store only what you need to store. It saves space.




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   18 / 35
Enter Iterators




        Maintain state.
        Transit between states.




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   19 / 35
A simple Fibonacci Iterator


 class Fibonacci :
     def __init__(self) :
         self.p, self.q = 0, 1
     def __iter__(self) :
         return self

         def __next__(self) :
             self.p, self.q = self.q, self.p + self.q
             return self.p

 f = Fibonacci()
 for i in range(10) :
     print(next(f))


P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   20 / 35
Enter Generators




        An easier way to be lazy.
        Define functions, but use yield instead of return.
        The generator picks up where it left off.




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python     September 25, 2009   21 / 35
A simpler Fibonacci Generator




 def Fibonacci() :
     p, q = 0, 1

         while True :
             p, q = q, p + q
             yield p




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   22 / 35
Outline



 1   Introduction


 2   Idioms
        Accumulation
        Forgiveness
        Laziness
        Comprehension
        Context
        Odds and Ends




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   23 / 35
What are comprehensions?




        A short-hand form for building:
                Lists [func(i) for i in sequence]
                Generators (func(i) for i in sequence)
                Sets {func(i) for i in sequence}
                Dicts {key : func(key) for key in sequence}




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   24 / 35
They’re short. What else?




        Comprehensions are fast.
        Faster than looping.




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   25 / 35
Outline



 1   Introduction


 2   Idioms
        Accumulation
        Forgiveness
        Laziness
        Comprehension
        Context
        Odds and Ends




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   26 / 35
Motivation




        A common pattern:
                Setup
                Try
                Except
                Finally




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   27 / 35
A common use case




 connection = connection_to_db(db_info)

 try :
     do_some_stuff_with_db(connection, data)
 except BorkedOperation :
     handle_it()
 finally :
     clean_up_the_mess()




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   28 / 35
The ”with” statement.




        Simplifies the above usage pattern.
        def insert_data(db_info, data) :
            with db_connection(db_info) as connection :
                do_some_stuff_with_db(db_info, data)
        Much simpler.
        But where did the complexity go?




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   29 / 35
Context Managers




        Classes that implement         enter       and     exit   methods.
        Encapsulates the relevant logic within these methods.




P.C. Shyamshankar (PyCon India 2009)    Idiomatic Python            September 25, 2009   30 / 35
In Context




         enter           method of the context manager is called, result stored in
        var.
        Block is executed.
           exit        method of the context manager is called.




P.C. Shyamshankar (PyCon India 2009)     Idiomatic Python        September 25, 2009   31 / 35
Outline



 1   Introduction


 2   Idioms
        Accumulation
        Forgiveness
        Laziness
        Comprehension
        Context
        Odds and Ends




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   32 / 35
Odds and Ends




        Enumerate, don’t index.
        Unpack tuples, don’t index.
        Assign to slices, don’t loop over them.
        Duck Type, don’t Check Type.
        Use your head.




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   33 / 35
DRY




        Don’t Repeat Yourself.
        itertools are meant to help you process data.
        collections are meant to help you hold data.




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   34 / 35
Thank you.




                                       That’s it.




P.C. Shyamshankar (PyCon India 2009)   Idiomatic Python   September 25, 2009   35 / 35

Más contenido relacionado

Último

Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform EngineeringMarcus Vechiato
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewDianaGray10
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseWSO2
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Paige Cruz
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsLeah Henrickson
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringWSO2
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...SOFTTECHHUB
 
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
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptxFIDO Alliance
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governanceWSO2
 

Último (20)

Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
 
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...
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 

Destacado

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Idiomatic Python

  • 1. Idiomatic Python P.C. Shyamshankar PyCon India 2009 September 25, 2009 P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 1 / 35
  • 2. Outline 1 Introduction 2 Idioms Accumulation Forgiveness Laziness Comprehension Context Odds and Ends P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 2 / 35
  • 3. The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren’t special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one, and preferably only one, obvious way to do it. Although that way may not be obvious at first unless you’re Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it’s a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea – let’s do more of those! P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 3 / 35
  • 4. Idioms An Unwritten Rule A common use-case. Usually to make the code better in some way: Readability Speed Resource Usage P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 4 / 35
  • 5. Outline 1 Introduction 2 Idioms Accumulation Forgiveness Laziness Comprehension Context Odds and Ends P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 5 / 35
  • 6. Outline 1 Introduction 2 Idioms Accumulation Forgiveness Laziness Comprehension Context Odds and Ends P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 6 / 35
  • 7. Putting strings together. Strings are immutable String addition creates copies. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 7 / 35
  • 8. Join, Don’t Add. s = ’’ for i in list_of_strings : s += i s = ’’.join(list_of_strings) P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 8 / 35
  • 9. That’s just what everyone says. String addition isn’t evil, just asymptotically slow. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 9 / 35
  • 10. Outline 1 Introduction 2 Idioms Accumulation Forgiveness Laziness Comprehension Context Odds and Ends P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 10 / 35
  • 11. EAFP It’s Easier to Ask Forgiveness than Permission. Asking permission is to LBYL But it depends on the context. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 11 / 35
  • 12. A Story of Keys in a Dict If the key is in the dict, increment its value. If not, set its value to 1. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 12 / 35
  • 13. Asking for Permission if key in my_dict : my_dict[key] += 1 else : my_dict[key] == 1 P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 13 / 35
  • 14. Asking for Forgiveness try : my_dict[key] += 1 except KeyError : my_dict[key] = 1 P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 14 / 35
  • 15. Choosing the right time Use the first approach, if you’re more likely to succeed. Use the second if you’re more likely to fail. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 15 / 35
  • 16. So many choices! my dict.get(key, 0) += 1 my dict.setdefault(key, []).append(value) my dict = collections.defaultdict(int) my dict = collections.Counter() P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 16 / 35
  • 17. Outline 1 Introduction 2 Idioms Accumulation Forgiveness Laziness Comprehension Context Odds and Ends P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 17 / 35
  • 18. Be Lazy! Compute only what you need to compute. It saves time. Store only what you need to store. It saves space. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 18 / 35
  • 19. Enter Iterators Maintain state. Transit between states. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 19 / 35
  • 20. A simple Fibonacci Iterator class Fibonacci : def __init__(self) : self.p, self.q = 0, 1 def __iter__(self) : return self def __next__(self) : self.p, self.q = self.q, self.p + self.q return self.p f = Fibonacci() for i in range(10) : print(next(f)) P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 20 / 35
  • 21. Enter Generators An easier way to be lazy. Define functions, but use yield instead of return. The generator picks up where it left off. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 21 / 35
  • 22. A simpler Fibonacci Generator def Fibonacci() : p, q = 0, 1 while True : p, q = q, p + q yield p P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 22 / 35
  • 23. Outline 1 Introduction 2 Idioms Accumulation Forgiveness Laziness Comprehension Context Odds and Ends P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 23 / 35
  • 24. What are comprehensions? A short-hand form for building: Lists [func(i) for i in sequence] Generators (func(i) for i in sequence) Sets {func(i) for i in sequence} Dicts {key : func(key) for key in sequence} P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 24 / 35
  • 25. They’re short. What else? Comprehensions are fast. Faster than looping. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 25 / 35
  • 26. Outline 1 Introduction 2 Idioms Accumulation Forgiveness Laziness Comprehension Context Odds and Ends P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 26 / 35
  • 27. Motivation A common pattern: Setup Try Except Finally P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 27 / 35
  • 28. A common use case connection = connection_to_db(db_info) try : do_some_stuff_with_db(connection, data) except BorkedOperation : handle_it() finally : clean_up_the_mess() P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 28 / 35
  • 29. The ”with” statement. Simplifies the above usage pattern. def insert_data(db_info, data) : with db_connection(db_info) as connection : do_some_stuff_with_db(db_info, data) Much simpler. But where did the complexity go? P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 29 / 35
  • 30. Context Managers Classes that implement enter and exit methods. Encapsulates the relevant logic within these methods. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 30 / 35
  • 31. In Context enter method of the context manager is called, result stored in var. Block is executed. exit method of the context manager is called. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 31 / 35
  • 32. Outline 1 Introduction 2 Idioms Accumulation Forgiveness Laziness Comprehension Context Odds and Ends P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 32 / 35
  • 33. Odds and Ends Enumerate, don’t index. Unpack tuples, don’t index. Assign to slices, don’t loop over them. Duck Type, don’t Check Type. Use your head. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 33 / 35
  • 34. DRY Don’t Repeat Yourself. itertools are meant to help you process data. collections are meant to help you hold data. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 34 / 35
  • 35. Thank you. That’s it. P.C. Shyamshankar (PyCon India 2009) Idiomatic Python September 25, 2009 35 / 35