SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Kürzlich hochgeladen

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 

Kürzlich hochgeladen (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 

Empfohlen

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
 

Empfohlen (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