Python 3000. Overview  Last week Python 3000 was released  Python 3000 == Python 3.0 == Py3k  Designed to break backwards compatibility with the 2.x.

Slides:



Advertisements
Similar presentations
Python 3000 and You Guido van Rossum EuroPython July 7, 2008.
Advertisements

Python 3000 (PyCon, 24-Feb-02007) Guido van Rossum
Python 3000 and You Guido van Rossum PyCon March 14, 2008.
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
Introduction to Python Week 15. Try It Out! Download Python from Any version will do for this class – By and large they are all mutually.
Bruce Beckles University of Cambridge Computing Service
Types in Ruby and other languages….  Classes and objects (vs prototypes)  Instance variables/encapsulation  Object creation  Object equality/comparison.
Adapted from Scott, Chapter 6:: Control Flow Programming Language Pragmatics Michael L. Scott.
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
Classes 2 COMPSCI 105 SS 2015 Principles of Computer Science.
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Compiler Construction
Chapter 9 Imperative and object-oriented languages 1.
Chapter 6 Structured Data Types Arrays Records. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Definitions data type –collection of data objects.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
1 Python Chapter 3 Reading strings and printing. © Samuel Marateck.
1 Type Type system for a programming language = –set of types AND – rules that specify how a typed program is allowed to behave Why? –to generate better.
Chapter 6 Structured Data Types Arrays Records. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Definitions data type –collection of data objects.
Introduction to Python (for C++ programmers). Background Information History – created in December 1989 by Guido van Rossum Interpreted Dynamically-typed.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
CIS Computer Programming Logic
CS61A Lecture 15 Object-Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Python misc. Typring: LBYL vs EAFP  How do you know you have a type error in a dynamic language like Python?  LBYL is “Look Before You Leap” -Programmer.
CSC 508 – Theory of Programming Languages, Spring, 2009 Week 3: Data Abstraction and Object Orientation.
Built-in Data Structures in Python An Introduction.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Last Week if statement print statement input builtin function strings and methods for loop.
Variables, Expressions, and Statements
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Python Functions.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Java Programming Java Basics. Data Types Java has two main categories of data types: –Primitive data types Built in data types Many very similar to C++
Types(1). Lecture 52 Type(1)  A type is a collection of values and operations on those values. Integer type  values..., -2, -1, 0, 1, 2,...  operations.
Prof. Hilfinger CS164 Lecture 51 The Pyth Language Lecture 5.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CS 261 – Data Structures Introduction to C Programming.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
Variables, Environments and Closures. Overview Touch on the notions of variable extent and scope Introduce the notions of lexical scope and dynamic.
RUBY by Ryan Chase.
Notes on Python Regular Expressions and parser generators (by D. Parson) These are the Python supplements to the author’s slides for Chapter 1 and Section.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
Announcements You will receive your scores back for Assignment 2 this week. You will have an opportunity to correct your code and resubmit it for partial.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
Quiz 4 Topics Aid sheet is supplied with quiz. Functions, loops, conditionals, lists – STILL. New topics: –Default and Keyword Arguments. –Sets. –Strings.
Heath Carroll Bill Hanczaryk Rich Porter.  A Theory of Type Polymorphism in Programming ◦ Robin Milner (1977)  Milner credited with introducing the.
Discover Python 3 Slavek Kabrda Presented by
Python 3000.
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Notes on Python Regular Expressions and parser generators (by D
Lecture 4: Type Systems.
Copyright (c) 2017 by Dr. E. Horvath
Expressions & Assignments
Variables, Environments and Closures
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Winter 2018 CISC101 12/1/2018 CISC101 Reminders
Type & Typeclass Syntax in function
Python Primer 1: Types and Operators
Python Review
INTRODUCTION to PERL PART 1.
Presentation transcript:

Python 3000

Overview  Last week Python 3000 was released  Python 3000 == Python 3.0 == Py3k  Designed to break backwards compatibility with the 2.x series to fix “language flaws”  Goal: reduce feature duplication by removing old ways of doing things  This is a big change and Python 2.x will continue in parallel for some years -An element of risk here: will it split the Python community?

Motivation, According to GVR  “Open source needs to move or die” —Matz (creator of Ruby)  To fix early, sticky design mistakes —e.g. classic classes, int division, print statement  Changing times: time/space trade-off —e.g. str/unicode, int/long  New paradigms come along —e.g. dict views, argument annotations

Benefits, according to GVR  More predictable Unicode handling  Smaller language —Makes “Python fits in your brain” more true  TOOWTDI (There’s Only One Way To Do It -- The Zen of Python) -see Perl's TIMTOWTDI (Tim Toady) – “There Is More Than One Way To Do It”  Common traps removed  Fewer surprises  Fewer exceptions

Major Breakages  Print function: print(a, b, file=sys.stderr)  Distinguish sharply btw. text and data —b"…" for bytes literals —"…" for (Unicode) str literals  Dict keys() returns a set view [+items()/values()]  No default, >= implementation  1/2 returns 0.5  Library cleanup

Print is a Function  print x, y-> print(x, y)  print x,-> print(x, end=" ")  print >>f, x-> print(x, file=f)

Dictionary Views  Inspired by Java Collections Framework  Remove.iterkeys(),.iteritems(),.itervalues()  Change.keys(),.items(),.values()  These return a dict view -Not an iterator -A lightweight object that can be iterated repeatedly -.keys(),.items() have set semantics -.values() has "collection" semantics —supports iteration and not much else

Default Comparison Changed  In Python 2.x the default comparisons are overly forgiving >>> 1 < "foo" True  In Py3k incomparable types raise an error >>> 1 < "foo" Traceback … TypeError: unorderable types: int() < str()  Rationale: 2.x default ordering is bogus -depends on type names -depends on addresses

All Strings are Unicode Strings  Java-like model: -strings (the str type) are always Unicode -separate bytes type -must explicitly specify encoding to go between these  Open issues: -implementation —fixed-width characters for O(1) indexing —maybe 3 internal widths: 1, 2, 4 byte characters —C API issues (many C APIs use C char* pointers) -optimize slicing and concatenation??? —lots of issues, supporters, detractors

Int/Long Unification  There is only one built-in integer type  Its name is int  Its implementation is like long in Python 2.x

Int Division Returns a Float  Always!  Same effect in 2.x with -from __future__ import division  Use // for int division

Function Annotations  P3k still uses dynamic typing  P3K allows optional function annotations that can be used for informal type declarations  You can attach a Python expression to describe -Each parameter in a function definition -The function’s return value  These are not part of Python’s semantics but can be used by other programs, e.g., for a type checker

Function Annotations  Example: Def posint(n: int) -> bool: return n > 0  The function object that posint is bound to will had an attribute named __annotation__ that will be the dictionary {‘n': int, 'return': bool}  A number of use cases are identified in the PEP including type checking

example >>> def posint(n: int) -> bool: return n > 0 >>> posint(10) True >>> posint.__annotations__ {'return':, 'n': } >>> int >>> dir(posint) ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Typing: LBYL vs EAFP  How do you know you have a type error in a dynamic language like Python?  LBYL is “Look Before You Leap” -Programmer explicitly checks types of values before processing, e.g., isinstance(x,int)  EAFP is “Easier to Ask Forgiveness that Permission” -Let Python raise an error when there is a problem  Which is better?

LBYL  LBYL -Adds a performance hit -Requires extra programming -Can detect errors early, before you program does something stupid with side-effects -Good for for some personalities -But it doesn’t play well with duck typing  EAFP -Maybe your errors will be noticed at an inopportune time

Nominative vs Structural  nominative type system -type compatibility and equivalence determined by explicit declarations or type names -E.g., C, C++, Java  Structural type system -type compatibility and equivalence determined by type's structure, not explicit declarations -e.g. Python’s duck typing -What counts on structure can vary – e.g. having a set of methods or attributes

Abstract Base Classes  Py3K adds Abstract Base Classes  You can define you own ‘abstract classes’ and specify their relationship to other classes  So you can create an ABC and ‘register’ other classes as subclasses from abc import ABCMeta class MyABC: __metaclass__ = ABCMeta MyABC.register(tuple)  Which makes these return True assert issubclass(tuple, MyABC) assert isinstance((), MyABC)

Define ABCs for Duck Types  This gives you a better way to extend the type system, if needed, to add types corresponding to duck types

The ‘2to3’ Tool   Context-free source code translator  Handles syntactic changes best —E.g. print; `…`; <>; except E, v:  Handles built-ins pretty well —E.g. d.keys(), xrange(), apply()  Has some inherant limitations -Doesn’t do type inferencing -Doesn’t follow variables in your code