SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
Why Python 3!
                               Finally Possible




Wednesday, October 10, 12
Why We Didn’t Switch

                            Python 3 is incompatible with Python 2

                            Performance was worse

                            Memory usage was higher

                            Most libraries and frameworks were not
                            ported



Wednesday, October 10, 12
Performance


                            Python 3.0 had a whole new IO library

                            Much cleaner, but...

                            Entirely written in Python

                            Fixed in Python 3.1




Wednesday, October 10, 12
Memory Usage

                            Mainly caused by all-Unicode all-the-time

                            Every string took 2 or 4 bytes per character

                            Often memory requirements for an app
                            doubled or worse

                            Fixed in Python 3.3



Wednesday, October 10, 12
Libraries and
                                    Frameworks

                            NumPy 1.5+ and SciPy 0.9+

                            Django 1.5+

                            Pyramid 1.3+

                            Six library used as a compatibility layer by
                            many libraries now



Wednesday, October 10, 12
OK, But Why Bother?

                            Cleaned up syntax, better library
                            organization, blah, blah, blah. But it does
                            make things better going forward.

                            Simpler string handling

                            Lot’s of cool new features




Wednesday, October 10, 12
Cleaned Up Syntax

                            except Exception,e -> except Exception as e

                            True, False and None are reserved words
                            now. Whew, that could have been ugly!

                            All classes are “new” classes

                            super() instead super(parent,self)

                            Annotations are cool!


Wednesday, October 10, 12
Simpler String Handling


                            All strings are Unicode

                            No more worrying about codecs

                            Flexible String Representation in Python 3.3
                            solves memory issues




Wednesday, October 10, 12
More Comprehensions


                            There are now dict and set comprehensions

                            {k: v for k, v in stuff if v} (Python 2.7+)

                            {k for k in list_of_stuff if k>0}




Wednesday, October 10, 12
New Syntax Tricks

                            Sets: {1,2,3}

                            Keyword only arguments:
                            def awesome(name, *, pumpItUp=False)

                            Extended unpacking:
                            a, b, *rest = range(5)

                            nonlocal is like global but for the enclosure



Wednesday, October 10, 12
Chained Exceptions

                            try:
                               a = divide(1,0)
                            except Exception as e:
                               raise ThatsNotGood() from e

                            Traceback shows both exceptions

                            Both exceptions also shown if you have an
                            exception in your exception handler



Wednesday, October 10, 12
Ordered Dictionaries

                            Normal dictionaries are random order

                            Can be a real problem for reading and
                            writing JSON since keys get scrambled

                            Ordered Dictionaries preserve insertion
                            order

                            Used by the JSON library



Wednesday, October 10, 12
Formatting Numbers


                            Easy to get commas now:

                              format(1234567, ‘,d’) -> ‘1,234,567’

                              format(1234567.89, ‘,.2f’) -> ‘1,234,567.89’




Wednesday, October 10, 12
Context Manager
                            Back-ported to Python 2.6 so use it now!

                            Manages lifetime. Use instead of try/finally.

                            with open(‘mylog.txt’) as infile:
                               error_lines=[]
                               for line in infile:
                                  if ‘ERROR’ in line:
                                       error_lines.append(line)

                            File closed as soon as with block ends

Wednesday, October 10, 12
contextlib
                        from contextlib import contextmanager

                        @contextmanager
                        def db_transaction(connection):
                            cursor = connection.cursor()
                            try:
                                 yield cursor
                            except:
                                 connection.rollback()
                                 raise
                            else:
                                 connection.commit()

                        db = DatabaseConnection()
                        with db_transaction(db) as cursor:
                            ...

Wednesday, October 10, 12
argparse

                            Much better library for handling command-
                            line arguments

                            Automatically generates help

                            Available for Python 2.6 so use it now

                            Really, check it out!



Wednesday, October 10, 12
concurrent.futures

                            Simplifies multithreading:

        import concurrent.futures, shutil

        with concurrent.futures.ThreadPoolExecutor(max_workers=4) as e:
            e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
            e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
            e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
            e.submit(shutil.copy, 'src4.txt', 'dest4.txt')




Wednesday, October 10, 12
New GIL
                            GIL is the great Achilles Heal of Python

                            Old GIL had pretty bad performance on
                            multicore boxes

                            New GIL in Python 3.2 is generally much
                            better. Performance was enough better for
                            me to abandon gevent!

                            Can still be ugly if you mix CPU-bound and
                            IO-bound code

Wednesday, October 10, 12
Annotations


                            Let you add some purely documentary tags
                            onto parameters and functions:

                              def digest(stuff: “iterable of numbers”,
                              non_zero:bool=False) -> hash:




Wednesday, October 10, 12
New in Python 3.3

                            venv - virtualenv is baked in now

                            Fancy new I/O exceptions. Instead of
                            OSError, now we get things like:

                              PermissionError

                              FileNotFoundError

                            More compact attribute dictionaries


Wednesday, October 10, 12
Biggest Gotcha Award


                            ‘print’ is a function now

                            dict.keys(), dict.values() and dict.items() return
                            generators instead of lists




Wednesday, October 10, 12
Questions?



                            Want to see an argparse example?

                            Email me: scott@codecobblers.com




Wednesday, October 10, 12

Weitere ähnliche Inhalte

Ähnlich wie Why Python 3

Rcos presentation
Rcos presentationRcos presentation
Rcos presentationmskmoorthy
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...JAX London
 
Python PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxPython PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxsushil155005
 
ZFS and FreeBSD Jails
ZFS and FreeBSD JailsZFS and FreeBSD Jails
ZFS and FreeBSD Jailsapeiron
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2sadhana312471
 
Python for Financial Data Analysis with pandas
Python for Financial Data Analysis with pandasPython for Financial Data Analysis with pandas
Python for Financial Data Analysis with pandasWes McKinney
 
Slides 111017220255-phpapp01
Slides 111017220255-phpapp01Slides 111017220255-phpapp01
Slides 111017220255-phpapp01Ken Mwai
 
Continuations in scala (incomplete version)
Continuations in scala (incomplete version)Continuations in scala (incomplete version)
Continuations in scala (incomplete version)Fuqiang Wang
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossumoscon2007
 
Taming Pythons with ZooKeeper
Taming Pythons with ZooKeeperTaming Pythons with ZooKeeper
Taming Pythons with ZooKeeperJyrki Pulliainen
 
Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010Matt Aimonetti
 
A Head Start on Python Language
A Head Start on Python Language A Head Start on Python Language
A Head Start on Python Language saggi_decembre
 

Ähnlich wie Why Python 3 (20)

Rcos presentation
Rcos presentationRcos presentation
Rcos presentation
 
StORM preview
StORM previewStORM preview
StORM preview
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...
 
Moose
MooseMoose
Moose
 
Python PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxPython PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptx
 
ZFS and FreeBSD Jails
ZFS and FreeBSD JailsZFS and FreeBSD Jails
ZFS and FreeBSD Jails
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Python for Financial Data Analysis with pandas
Python for Financial Data Analysis with pandasPython for Financial Data Analysis with pandas
Python for Financial Data Analysis with pandas
 
Slides 111017220255-phpapp01
Slides 111017220255-phpapp01Slides 111017220255-phpapp01
Slides 111017220255-phpapp01
 
06 data
06 data06 data
06 data
 
Continuations in scala (incomplete version)
Continuations in scala (incomplete version)Continuations in scala (incomplete version)
Continuations in scala (incomplete version)
 
XQuery Design Patterns
XQuery Design PatternsXQuery Design Patterns
XQuery Design Patterns
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossum
 
Noboxing plugin
Noboxing pluginNoboxing plugin
Noboxing plugin
 
55j7
55j755j7
55j7
 
Taming Pythons with ZooKeeper
Taming Pythons with ZooKeeperTaming Pythons with ZooKeeper
Taming Pythons with ZooKeeper
 
Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
A Head Start on Python Language
A Head Start on Python Language A Head Start on Python Language
A Head Start on Python Language
 

Mehr von pythonsd

Pep 465 - Matrix Multiplication in Python
Pep 465 - Matrix Multiplication in PythonPep 465 - Matrix Multiplication in Python
Pep 465 - Matrix Multiplication in Pythonpythonsd
 
Sqlalchemy lightning talk
Sqlalchemy lightning talkSqlalchemy lightning talk
Sqlalchemy lightning talkpythonsd
 
PythonSD Test Driven Django Development Workshop
PythonSD Test Driven Django Development WorkshopPythonSD Test Driven Django Development Workshop
PythonSD Test Driven Django Development Workshoppythonsd
 
Matplotlib demo code
Matplotlib demo codeMatplotlib demo code
Matplotlib demo codepythonsd
 
Matplotlib presentation 20 apr2013 final
Matplotlib presentation 20 apr2013   finalMatplotlib presentation 20 apr2013   final
Matplotlib presentation 20 apr2013 finalpythonsd
 
Blaze the-evolution-of-numpy
Blaze the-evolution-of-numpyBlaze the-evolution-of-numpy
Blaze the-evolution-of-numpypythonsd
 
Django production
Django productionDjango production
Django productionpythonsd
 
Django Toolbox
Django ToolboxDjango Toolbox
Django Toolboxpythonsd
 

Mehr von pythonsd (8)

Pep 465 - Matrix Multiplication in Python
Pep 465 - Matrix Multiplication in PythonPep 465 - Matrix Multiplication in Python
Pep 465 - Matrix Multiplication in Python
 
Sqlalchemy lightning talk
Sqlalchemy lightning talkSqlalchemy lightning talk
Sqlalchemy lightning talk
 
PythonSD Test Driven Django Development Workshop
PythonSD Test Driven Django Development WorkshopPythonSD Test Driven Django Development Workshop
PythonSD Test Driven Django Development Workshop
 
Matplotlib demo code
Matplotlib demo codeMatplotlib demo code
Matplotlib demo code
 
Matplotlib presentation 20 apr2013 final
Matplotlib presentation 20 apr2013   finalMatplotlib presentation 20 apr2013   final
Matplotlib presentation 20 apr2013 final
 
Blaze the-evolution-of-numpy
Blaze the-evolution-of-numpyBlaze the-evolution-of-numpy
Blaze the-evolution-of-numpy
 
Django production
Django productionDjango production
Django production
 
Django Toolbox
Django ToolboxDjango Toolbox
Django Toolbox
 

Why Python 3

  • 1. Why Python 3! Finally Possible Wednesday, October 10, 12
  • 2. Why We Didn’t Switch Python 3 is incompatible with Python 2 Performance was worse Memory usage was higher Most libraries and frameworks were not ported Wednesday, October 10, 12
  • 3. Performance Python 3.0 had a whole new IO library Much cleaner, but... Entirely written in Python Fixed in Python 3.1 Wednesday, October 10, 12
  • 4. Memory Usage Mainly caused by all-Unicode all-the-time Every string took 2 or 4 bytes per character Often memory requirements for an app doubled or worse Fixed in Python 3.3 Wednesday, October 10, 12
  • 5. Libraries and Frameworks NumPy 1.5+ and SciPy 0.9+ Django 1.5+ Pyramid 1.3+ Six library used as a compatibility layer by many libraries now Wednesday, October 10, 12
  • 6. OK, But Why Bother? Cleaned up syntax, better library organization, blah, blah, blah. But it does make things better going forward. Simpler string handling Lot’s of cool new features Wednesday, October 10, 12
  • 7. Cleaned Up Syntax except Exception,e -> except Exception as e True, False and None are reserved words now. Whew, that could have been ugly! All classes are “new” classes super() instead super(parent,self) Annotations are cool! Wednesday, October 10, 12
  • 8. Simpler String Handling All strings are Unicode No more worrying about codecs Flexible String Representation in Python 3.3 solves memory issues Wednesday, October 10, 12
  • 9. More Comprehensions There are now dict and set comprehensions {k: v for k, v in stuff if v} (Python 2.7+) {k for k in list_of_stuff if k>0} Wednesday, October 10, 12
  • 10. New Syntax Tricks Sets: {1,2,3} Keyword only arguments: def awesome(name, *, pumpItUp=False) Extended unpacking: a, b, *rest = range(5) nonlocal is like global but for the enclosure Wednesday, October 10, 12
  • 11. Chained Exceptions try: a = divide(1,0) except Exception as e: raise ThatsNotGood() from e Traceback shows both exceptions Both exceptions also shown if you have an exception in your exception handler Wednesday, October 10, 12
  • 12. Ordered Dictionaries Normal dictionaries are random order Can be a real problem for reading and writing JSON since keys get scrambled Ordered Dictionaries preserve insertion order Used by the JSON library Wednesday, October 10, 12
  • 13. Formatting Numbers Easy to get commas now: format(1234567, ‘,d’) -> ‘1,234,567’ format(1234567.89, ‘,.2f’) -> ‘1,234,567.89’ Wednesday, October 10, 12
  • 14. Context Manager Back-ported to Python 2.6 so use it now! Manages lifetime. Use instead of try/finally. with open(‘mylog.txt’) as infile: error_lines=[] for line in infile: if ‘ERROR’ in line: error_lines.append(line) File closed as soon as with block ends Wednesday, October 10, 12
  • 15. contextlib from contextlib import contextmanager @contextmanager def db_transaction(connection): cursor = connection.cursor() try: yield cursor except: connection.rollback() raise else: connection.commit() db = DatabaseConnection() with db_transaction(db) as cursor: ... Wednesday, October 10, 12
  • 16. argparse Much better library for handling command- line arguments Automatically generates help Available for Python 2.6 so use it now Really, check it out! Wednesday, October 10, 12
  • 17. concurrent.futures Simplifies multithreading: import concurrent.futures, shutil with concurrent.futures.ThreadPoolExecutor(max_workers=4) as e: e.submit(shutil.copy, 'src1.txt', 'dest1.txt') e.submit(shutil.copy, 'src2.txt', 'dest2.txt') e.submit(shutil.copy, 'src3.txt', 'dest3.txt') e.submit(shutil.copy, 'src4.txt', 'dest4.txt') Wednesday, October 10, 12
  • 18. New GIL GIL is the great Achilles Heal of Python Old GIL had pretty bad performance on multicore boxes New GIL in Python 3.2 is generally much better. Performance was enough better for me to abandon gevent! Can still be ugly if you mix CPU-bound and IO-bound code Wednesday, October 10, 12
  • 19. Annotations Let you add some purely documentary tags onto parameters and functions: def digest(stuff: “iterable of numbers”, non_zero:bool=False) -> hash: Wednesday, October 10, 12
  • 20. New in Python 3.3 venv - virtualenv is baked in now Fancy new I/O exceptions. Instead of OSError, now we get things like: PermissionError FileNotFoundError More compact attribute dictionaries Wednesday, October 10, 12
  • 21. Biggest Gotcha Award ‘print’ is a function now dict.keys(), dict.values() and dict.items() return generators instead of lists Wednesday, October 10, 12
  • 22. Questions? Want to see an argparse example? Email me: scott@codecobblers.com Wednesday, October 10, 12