10 awesome features of Python that you can't use because you refuse to upgrade to Python 3
|
|
|
- Moris Charles
- 10 years ago
- Views:
Transcription
1 10 awesome features of Python that you can't use because you refuse to upgrade to Python 3 1 / /72
2 10 awesome features of Python that you can't use because you refuse to upgrade to Python 3 or Turning it up to 11! 2 / /72
3 10 awesome features of Python that you can't use because you refuse to upgrade to Python 3 or Turning it up to 11! 3 / /72
4 Prelude Last month (March) APUG: only three people use Python 3 (including me) Lots of new features of Python 3. Some have been backported to Python 2.7. (like dictionary/set comprehensions or set literals, future.print_function) But there's more than that. New features that you can't use unless you are in Python 3. New syntax. New interpreter behavior. Standard library fixes. And it's more than bytes/unicode... 4 / /72
5 Feature 0: Matrix Multiplication (feature 0 because you can't actually use it yet) PEP 465 In Python 3.5, you'll be able to replace >>> a = np.array([[1, 0], [0, 1]]) >>> b = np.array([[4, 1], [2, 2]]) >>> np.dot(a, b) array([[4, 1], [2, 2]]) with >>> a = np.array([[1, 0], [0, 1]]) >>> b = np.array([[4, 1], [2, 2]]) >>> b array([[4, 1], [2, 2]]) Any object can override matmul to 5 / /72
6 Feature 1: Advanced unpacking You can already do this: >>> a, b = range(2) >>> a 0 >>> b 1 6 / /72
7 Feature 1: Advanced unpacking You can already do this: >>> a, b = range(2) >>> a 0 >>> b 1 Now you can do this: >>> a, b, *rest = range(10) >>> a 0 >>> b 1 >>> rest [2, 3, 4, 5, 6, 7, 8, 9] 7 / /72
8 Feature 1: Advanced unpacking You can already do this: >>> a, b = range(2) >>> a 0 >>> b 1 Now you can do this: >>> a, b, *rest = range(10) >>> a 0 >>> b 1 >>> rest [2, 3, 4, 5, 6, 7, 8, 9] *rest can go anywhere: >>> a, *rest, b = range(10) >>> a 0 >>> b 9 >>> rest [1, 2, 3, 4, 5, 6, 7, 8] >>> *rest, b = range(10) >> rest [0, 1, 2, 3, 4, 5, 6, 7, 8] >>> b 9 8 / /72
9 Feature 1: Advanced unpacking Get the first and last lines of a file >>> with open("using_python_to_profit") as f:... first, *_, last = f.readlines() >>> first 'Step 1: Use Python 3\n' >>> last 'Step 10: Profit!\n' 9 / /72
10 Feature 1: Advanced unpacking Get the first and last lines of a file >>> with open("using_python_to_profit") as f:... first, *_, last = f.readlines() >>> first 'Step 1: Use Python 3\n' >>> last 'Step 10: Profit!\n' Refactor your functions def f(a, b, *args): stuff def f(*args): a, b, *args = args stuff 10 / /72
11 Feature 2: Keyword only arguments def f(a, b, *args, option=true): / /72
12 Feature 2: Keyword only arguments def f(a, b, *args, option=true):... option comes after *args. 12 / /72
13 Feature 2: Keyword only arguments def f(a, b, *args, option=true):... option comes after *args. The only way to access it is to explicitly call f(a, b, option=true) 13 / /72
14 Feature 2: Keyword only arguments def f(a, b, *args, option=true):... option comes after *args. The only way to access it is to explicitly call f(a, b, option=true) You can write just a * if you don't want to collect *args. def f(a, b, *, option=true): / /72
15 Feature 2: Keyword only arguments No more, "Oops, I accidentally passed too many arguments to the function, and one of them was swalled by a keyword argument". def sum(a, b, biteme=false): if biteme: shutil.rmtree('/') else: return a + b >>> sum(1, 2) 3 >>> sum(1, 2, 3) 15 / /72
16 Feature 2: Keyword only arguments No more, "Oops, I accidentally passed too many arguments to the function, and one of them was swalled by a keyword argument". def sum(a, b, biteme=false): if biteme: shutil.rmtree('/') else: return a + b >>> sum(1, 2) 3 >>> sum(1, 2, 3) 16 / /72
17 Feature 2: Keyword only arguments Instead write def sum(a, b, *, biteme=false): if biteme: shutil.rmtree('/') else: return a + b >>> sum(1, 2, 3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sum() takes 2 positional arguments but 3 were given 17 / /72
18 Feature 2: Keyword only arguments Instead write def sum(a, b, *, biteme=false): if biteme: shutil.rmtree('/') else: return a + b >>> sum(1, 2, 3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sum() takes 2 positional arguments but 3 were given 18 / /72
19 Feature 2: Keyword only arguments Or, "I reordered the keyword arguments of a function, but something was implicitly passing in arguments expecting the order" Example: def maxall(iterable, key=none): """ A list of all max items from the iterable """ key = key or (lambda x: x) m = max(iterable, key=key) return [i for i in iterable if key(i) == key(m)] >>> maxall(['a', 'ab', 'bc'], len) ['ab', 'bc'] 19 / /72
20 Feature 2: Keyword only arguments The max builtin supports max(a, b, c). We should allow that too. def maxall(*args, key=none): """ A list of all max items from the iterable """ if len(args) == 1: iterable = args[0] else: iterable = args key = key or (lambda x: x) m = max(iterable, key=key) return [i for i in iterable if key(i) == key(m)] We just broke any code that passed in the key as a second argument without using the keyword. >>> maxall(['a', 'ab', 'ac'], len) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 10, in maxall TypeError: unorderable types: builtin_function_or_method() > list() (Actually in Python 2 it would just return ['a', 'ab', 'ac'], see feature 6). By the way, max shows that this is already possible in Python 2, but only if you write your function in C. Obviously, we should have used maxall(iterable, *, key=none) to begin with. 20 / /72
21 Feature 2: Keyword only arguments You can make your APIs "future change proof". Stupid example: def extendto(value, shorter, longer): """ Extend list `shorter` to the length of list `longer` with `value` """ if len(shorter) > len(longer): raise ValueError('The `shorter` list is longer than the `longer` list') a.extend([value]*(len(longer) - len(shorter))) >>> a = [1, 2] >>> b = [1, 2, 3, 4, 5] >>> extendto(10, a, b) >>> a [1, 2, 10, 10, 10] 21 / /72
22 Feature 2: Keyword only arguments You can make your APIs "future change proof". Stupid example: def extendto(value, shorter, longer): """ Extend list `shorter` to the length of list `longer` with `value` """ if len(shorter) > len(longer): raise ValueError('The `shorter` list is longer than the `longer` list') a.extend([value]*(len(longer) - len(shorter))) >>> a = [1, 2] >>> b = [1, 2, 3, 4, 5] >>> extendto(10, a, b) >>> a [1, 2, 10, 10, 10] Hmm, maybe it makes more sense for longer to come before shorter... Too bad, you'll break the code. 22 / /72
23 Feature 2: Keyword only arguments In Python 3, you can use def extendto(value, *, shorter=none, longer=none): """ Extend list `shorter` to the length of list `longer` with `value` """ if shorter is None or longer is None: raise TypeError('`shorter` and `longer` must be specified') if len(shorter) > len(longer): raise ValueError('The `shorter` list is longer than the `longer` list') a.extend([value]*(len(longer) - len(shorter))) Now, a and b have to be passed in as extendto(10, shorter=a, longer=b). 23 / /72
24 Feature 2: Keyword only arguments In Python 3, you can use def extendto(value, *, shorter=none, longer=none): """ Extend list `shorter` to the length of list `longer` with `value` """ if shorter is None or longer is None: raise TypeError('`shorter` and `longer` must be specified') if len(shorter) > len(longer): raise ValueError('The `shorter` list is longer than the `longer` list') a.extend([value]*(len(longer) - len(shorter))) Now, a and b have to be passed in as extendto(10, shorter=a, longer=b). Or if you prefer, extendto(10, longer=b, shorter=a). 24 / /72
25 Feature 2: Keyword only arguments Add new keyword arguments without breaking API. Python 3 did this in the standard library. 25 / /72
26 Feature 2: Keyword only arguments Add new keyword arguments without breaking API. Python 3 did this in the standard library. For example, functions in os have follow_symlinks option. 26 / /72
27 Feature 2: Keyword only arguments Add new keyword arguments without breaking API. Python 3 did this in the standard library. For example, functions in os have follow_symlinks option. So you can just use os.stat(file, follow_symlinks=false) instead of os.lstat. 27 / /72
28 Feature 2: Keyword only arguments Add new keyword arguments without breaking API. Python 3 did this in the standard library. For example, functions in os have follow_symlinks option. So you can just use os.stat(file, follow_symlinks=false) instead of os.lstat. In case that sounds more verbose, it lets you do s = os.stat(file, follow_symlinks=some_condition) instead of if some_condition: s = os.stat(file) else: s = os.lstat(file) 28 / /72
29 Feature 2: Keyword only arguments Add new keyword arguments without breaking API. Python 3 did this in the standard library. For example, functions in os have follow_symlinks option. So you can just use os.stat(file, follow_symlinks=false) instead of os.lstat. In case that sounds more verbose, it lets you do s = os.stat(file, follow_symlinks=some_condition) instead of if some_condition: s = os.stat(file) else: s = os.lstat(file) But os.stat(file, some_condition) doesn't work. Keeps you from thinking it's a two-argument function. 29 / /72
30 Feature 2: Keyword only arguments In Python 2, you have to use **kwargs and do the handling yourself. 30 / /72
31 Feature 2: Keyword only arguments In Python 2, you have to use **kwargs and do the handling yourself. Lot's of ugly option = kwargs.pop(true) at the top of your functions. 31 / /72
32 Feature 2: Keyword only arguments In Python 2, you have to use **kwargs and do the handling yourself. Lot's of ugly option = kwargs.pop(true) at the top of your functions. No longer self documenting. 32 / /72
33 Feature 2: Keyword only arguments In Python 2, you have to use **kwargs and do the handling yourself. Lot's of ugly option = kwargs.pop(true) at the top of your functions. No longer self documenting. If you somehow are writing for a Python 3 only codebase, I highly recommend making all your keyword arguments keyword only, especially keyword arguments that represent "options". 33 / /72
34 Feature 3: Chained exceptions Situation: you catch an exception with except, do something, and then raise a different exception. def mycopy(source, dest): try: shutil.copy2(source, dest) except OSError: # We don't have permissions. More on this later raise NotImplementedError("automatic sudo injection") Problem: You lose the original traceback >>> mycopy('noway', 'noway2') >>> mycopy(1, 2) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in mycopy NotImplementedError: automatic sudo injection 34 / /72
35 Feature 3: Chained exceptions Situation: you catch an exception with except, do something, and then raise a different exception. def mycopy(source, dest): try: shutil.copy2(source, dest) except OSError: # We don't have permissions. More on this later raise NotImplementedError("automatic sudo injection") Problem: You lose the original traceback >>> mycopy('noway', 'noway2') >>> mycopy(1, 2) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in mycopy NotImplementedError: automatic sudo injection What happened with the OSError? 35 / /72
36 Feature 3: Chained exceptions Python 3 shows you the whole chain of exceptions: mycopy('noway', 'noway2') Traceback (most recent call last): File "<stdin>", line 3, in mycopy File "/Users/aaronmeurer/anaconda3/lib/python3.3/shutil.py", line 243, in copy2 copyfile(src, dst, follow_symlinks=follow_symlinks) File "/Users/aaronmeurer/anaconda3/lib/python3.3/shutil.py", line 109, in copyfile with open(src, 'rb') as fsrc: PermissionError: [Errno 13] Permission denied: 'noway' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in mycopy NotImplementedError: automatic sudo injection 36 / /72
37 Feature 3: Chained exceptions Python 3 shows you the whole chain of exceptions: mycopy('noway', 'noway2') Traceback (most recent call last): File "<stdin>", line 3, in mycopy File "/Users/aaronmeurer/anaconda3/lib/python3.3/shutil.py", line 243, in copy2 copyfile(src, dst, follow_symlinks=follow_symlinks) File "/Users/aaronmeurer/anaconda3/lib/python3.3/shutil.py", line 109, in copyfile with open(src, 'rb') as fsrc: PermissionError: [Errno 13] Permission denied: 'noway' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in mycopy NotImplementedError: automatic sudo injection You can also do this manually using raise from raise exception from e >>> raise NotImplementedError from OSError OSError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<stdin>", line 1, in <module> NotImplementedError 37 / /72
38 Feature 4: Fine grained OSError subclasses The code I just showed you is wrong. It catches OSError and assumes it is a permission error. But OSError can be a lot of things (file not found, is a directory, is not a directory, broken pipe,...) You really have to do import errno def mycopy(source, dest): try: shutil.copy2(source, dest) except OSError as e: if e.errno in [errno.eperm, errno.eacces]: raise NotImplementedError("automatic sudo injection") else: raise 38 / /72
39 Feature 4: Fine grained OSError subclasses The code I just showed you is wrong. It catches OSError and assumes it is a permission error. But OSError can be a lot of things (file not found, is a directory, is not a directory, broken pipe,...) You really have to do import errno def mycopy(source, dest): try: shutil.copy2(source, dest) except OSError as e: if e.errno in [errno.eperm, errno.eacces]: raise NotImplementedError("automatic sudo injection") else: raise Wow. That sucks. 39 / /72
40 Feature 4: Fine grained OSError subclasses The code I just showed you is wrong. It catches OSError and assumes it is a permission error. But OSError can be a lot of things (file not found, is a directory, is not a directory, broken pipe,...) You really have to do import errno def mycopy(source, dest): try: shutil.copy2(source, dest) except OSError as e: if e.errno in [errno.eperm, errno.eacces]: raise NotImplementedError("automatic sudo injection") else: raise Wow. That sucks. 40 / /72
41 Feature 4: Fine grained OSError subclasses Python 3 fixes this by adding a ton of new exceptions. You can just do def mycopy(source, dest): try: shutil.copy2(source, dest) except PermissionError: raise NotImplementedError("automatic sudo injection") (Don't worry, PermissionError subclasses from OSError and still has.errno. Old code will still work). 41 / /72
42 Feature 5: Everything is an iterator This is the hardest one to sell. Iterators exist in Python 2 as well. But you have to use them. Don't write range or zip or dict.values or / /72
43 Feature 5: Everything is an iterator If you do / /72
44 Feature 5: Everything is an iterator If you do... def naivesum(n): """ Naively sum the first N integers """ A = 0 for i in range(n + 1): A += i return A 44 / /72
45 Feature 5: Everything is an iterator If you do... def naivesum(n): """ Naively sum the first N integers """ A = 0 for i in range(n + 1): A += i return A In [3]: timeit naivesum( ) 10 loops, best of 3: 61.4 ms per loop 45 / /72
46 Feature 5: Everything is an iterator If you do... def naivesum(n): """ Naively sum the first N integers """ A = 0 for i in range(n + 1): A += i return A In [3]: timeit naivesum( ) 10 loops, best of 3: 61.4 ms per loop In [4]: timeit naivesum( ) 1 loops, best of 3: 622 ms per loop 46 / /72
47 Feature 5: Everything is an iterator If you do... def naivesum(n): """ Naively sum the first N integers """ A = 0 for i in range(n + 1): A += i return A In [3]: timeit naivesum( ) 10 loops, best of 3: 61.4 ms per loop In [4]: timeit naivesum( ) 1 loops, best of 3: 622 ms per loop In [5]: timeit naivesum( ) 47 / /72
48 Feature 5: Everything is an iterator If you do... def naivesum(n): """ Naively sum the first N integers """ A = 0 for i in range(n + 1): A += i return A In [3]: timeit naivesum( ) 10 loops, best of 3: 61.4 ms per loop In [4]: timeit naivesum( ) 1 loops, best of 3: 622 ms per loop In [5]: timeit naivesum( ) 48 / /72
49 Feature 5: Everything is an iterator 49 / /72
50 Feature 5: Everything is an iterator Instead write some variant (xrange, itertools.izip, dict.itervalues,...). Inconsistant API anyone? 50 / /72
51 Feature 5: Everything is an iterator In Python 3, range, zip, map, dict.values, etc. are all iterators. If you want a list, just wrap the result with list. Explicit is better than implicit. Harder to write code that accidentally uses too much memory, because the input was bigger than you expected. 51 / /72
52 Feature 6: No more comparison of everything to everything In Python 2, you can do >>> max(['one', 2]) # One *is* the lonliest number 'one' 52 / /72
53 Feature 6: No more comparison of everything to everything In Python 2, you can do >>> max(['one', 2]) # One *is* the lonliest number 'one' Hurray. I just disproved math! 53 / /72
54 Feature 6: No more comparison of everything to everything It's because in Python 2, you can < compare anything to anything. >>> 'abc' > 123 True >>> None > all False 54 / /72
55 Feature 6: No more comparison of everything to everything It's because in Python 2, you can < compare anything to anything. >>> 'abc' > 123 True >>> None > all False In Python 3, you can't do this: >>> 'one' > 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: str() > int() This avoids subtle bugs, e.g., from not coercing all types from int to str or visa versa. Especially when you use > implicitly, like with max or sorted. In Python 2: >>> sorted(['1', 2, '3']) [2, '1', '3'] 55 / /72
56 Feature 7: yield from Pretty great if you use generators Instead of writing for i in gen(): yield i Just write yield from gen() Easily refactor generators into subgenerators. 56 / /72
57 Feature 7: yield from Makes it easier to turn everything into a generator. See "Feature 5: Everything is an iterator" above for why you should do this. Instead of accumulating a list, just yield or yield from. Bad def dup(n): A = [] for i in range(n): A.extend([i, i]) return A Good def dup(n): for i in range(n): yield i yield i Better def dup(n): for i in range(n): yield from [i, i] 57 / /72
58 Feature 7: yield from In case you don't know, generators are awesome because: Only one value is computed at a time. Low memory impact (see range example above). Can break in the middle. Don't have to compute everything just to find out you needed none of it. Compute just what you need. If you often don't need it all, you can gain a lot of performance here. If you need a list (e.g., for slicing), just call list() on the generator. Function state is "saved" between yields. This leads to interesting possibilities, a. la. coroutines / /72
59 Feature 8: asyncio Uses new coroutines features and saved state of generators to do asynchronous IO. # Taken from Guido's slides from Tulip: Async I/O for Python 3 by Guido # van Rossum, at LinkedIn, Mountain View, Jan 23, def fetch(host, port): r,w = yield from open_connection(host,port) w.write(b'get /HTTP/1.0\r\n\r\n ') while (yield from r.readline()).decode('latin-1').strip(): pass body=yield from r.read() return def start(): data = yield from fetch('python.org', 80) print(data.decode('utf-8')) 59 / /72
60 Feature 8: asyncio Uses new coroutines features and saved state of generators to do asynchronous IO. # Taken from Guido's slides from Tulip: Async I/O for Python 3 by Guido # van Rossum, at LinkedIn, Mountain View, Jan 23, def fetch(host, port): r,w = yield from open_connection(host,port) w.write(b'get /HTTP/1.0\r\n\r\n ') while (yield from r.readline()).decode('latin-1').strip(): pass body=yield from r.read() return def start(): data = yield from fetch('python.org', 80) print(data.decode('utf-8')) Not going to lie to you. I still don't get this. 60 / /72
61 Feature 8: asyncio Uses new coroutines features and saved state of generators to do asynchronous IO. # Taken from Guido's slides from Tulip: Async I/O for Python 3 by Guido # van Rossum, at LinkedIn, Mountain View, Jan 23, def fetch(host, port): r,w = yield from open_connection(host,port) w.write(b'get /HTTP/1.0\r\n\r\n ') while (yield from r.readline()).decode('latin-1').strip(): pass body=yield from r.read() return def start(): data = yield from fetch('python.org', 80) print(data.decode('utf-8')) Not going to lie to you. I still don't get this. It's OK, though. Even David Beazley had a hard time with it: 61 / /72
62 Feature 9: Standard library additions faulthandler Display (limited) tracebacks, even when Python dies the hard way. Won't work with kill -9, but does work with, e.g., segfaults. import faulthandler faulthandler.enable() def killme(): # Taken from import sys from ctypes import CDLL # This will crash a Linux or Mac system; equivalent calls can be made on # Windows dll = 'dylib' if sys.platform == 'darwin' else 'so.6' libc = CDLL("libc.%s" % dll) libc.time(-1) # BOOM!! killme() $python test.py Fatal Python error: Segmentation fault Current thread 0x00007fff781b6310: File "test.py", line 11 in killme File "test.py", line 13 in <module> Segmentation fault: 11 Or kill -6 (SIGABRT) Can also enable with python -X faulthandler 62 / /72
63 Feature 9: Standard library additions ipaddress Exactly that. IP addresses. >>> ipaddress.ip_address(' ') IPv4Address(' ') >>> ipaddress.ip_address('2001:db8::') IPv6Address('2001:db8::') Just another thing you don't want to roll yourself. 63 / /72
64 Feature 9: Standard library additions functools.lru_cache A LRU cache decorator for your functions. From def get_pep(num): 'Retrieve text of a Python Enhancement Proposal' resource = ' % num try: with urllib.request.urlopen(resource) as s: return s.read() except urllib.error.httperror: return 'Not Found' >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:... pep = get_pep(n)... print(n, len(pep)) >>> get_pep.cache_info() CacheInfo(hits=3, misses=8, maxsize=32, currsize=8) 64 / /72
65 Feature 9: Standard library additions enum Finally, an enumerated type in the standard library. Python 3.4 only. >>> from enum import Enum >>> class Color(Enum):... red = 1... green = 2... blue = 3... Uses some magic that is only possible in Python 3 (due to metaclass changes): >>> class Shape(Enum):... square = 2... square = 3... Traceback (most recent call last):... TypeError: Attempted to reuse key: 'square' 65 / /72
66 Feature 10: Fun Unicode variable names >>> résumé = "knows Python" >>> π = math.pi 66 / /72
67 Feature 10: Fun Unicode variable names >>> résumé = "knows Python" >>> π = math.pi Sorry, letter-like characters only. = "beer" does not work. 67 / /72
68 Feature 10: Fun Unicode variable names >>> résumé = "knows Python" >>> π = math.pi Sorry, letter-like characters only. = "beer" does not work. Function annotations def f(a: stuff, b: stuff = 2) -> result:... Annotations can be arbitrary Python objects. Python doesn't do anything with the annotations other than put them in an annotations dictionary. >>> def f(x: int) -> float:... pass... >>> f. annotations {'return': <class 'float'>, 'x': <class 'int'>} But it leaves open the possiblity for library authors to do fun things. Example, IPython 2.0 widgets. Run IPython notebook (in Python 3) from IPython git checkout and open 68 / /72
69 Feature 11: Unicode and bytes In Python 2, str acts like bytes of data. There is also unicode type to represent Unicode strings. 69 / /72
70 Feature 11: Unicode and bytes In Python 2, str acts like bytes of data. There is also unicode type to represent Unicode strings. In Python 3, str is a string. bytes are bytes. There is no unicode. str strings are Unicode. 70 / /72
71 Discuss 71 / /72
72 Slides were made with All images have been blatenly stolen from the internet. Source for slides can be found at I am Aaron Meurer (@asmeurer). I gave this presentation on April 9, 2014 at APUG. If you are in Austin, TX and you enjoy Python, you should come to APUG! 72 / /72
Introduction to Python
Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment
Chapter 3 Writing Simple Programs. What Is Programming? Internet. Witin the web server we set lots and lots of requests which we need to respond to
Chapter 3 Writing Simple Programs Charles Severance Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License. http://creativecommons.org/licenses/by/3.0/.
University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python
Introduction Welcome to our Python sessions. University of Hull Department of Computer Science Wrestling with Python Week 01 Playing with Python Vsn. 1.0 Rob Miles 2013 Please follow the instructions carefully.
A: We really embarrassed ourselves last night at that business function.
Dialog: VIP LESSON 049 - Future of Business A: We really embarrassed ourselves last night at that business function. B: What are you talking about? A: We didn't even have business cards to hand out. We
Introduction to Python
Introduction to Python Sophia Bethany Coban Problem Solving By Computer March 26, 2014 Introduction to Python Python is a general-purpose, high-level programming language. It offers readable codes, and
Python 2 and 3 compatibility testing via optional run-time type checking
Python 2 and 3 compatibility testing via optional run-time type checking Raoul-Gabriel Urma Work carried out during a Google internship & PhD https://github.com/google/pytypedecl Python 2 vs. Python 3
Crash Dive into Python
ECPE 170 University of the Pacific Crash Dive into Python 2 Lab Schedule Ac:vi:es Assignments Due Today Lab 11 Network Programming Due by Dec 1 st 5:00am Python Lab 12 Next Week Due by Dec 8 th 5:00am
Things you didn't know about Python
Things you didn't know about Python a presentation by Armin Ronacher for PyCon South Africa 2012 @mitsuhiko http://lucumr.pocoo.org/ Things you didn't know about Python might already know computers a presentation
Crash Dive into Python
ECPE 170 University of the Pacific Crash Dive into Python 2 Lab Schedule Ac:vi:es Assignments Due Today Lab 8 Python Due by Oct 26 th 5:00am Endianness Lab 9 Tuesday Due by Nov 2 nd 5:00am Network programming
Python Loops and String Manipulation
WEEK TWO Python Loops and String Manipulation Last week, we showed you some basic Python programming and gave you some intriguing problems to solve. But it is hard to do anything really exciting until
pyownet Documentation
pyownet Documentation Release 0.10.0 Stefano Miccoli March 30, 2016 Contents 1 Contents 3 1.1 Introduction............................................. 3 1.2 Installation..............................................
Python Programming: An Introduction To Computer Science
Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e 1 Objectives æ To understand the concept of Boolean expressions and the bool data
Intro to scientific programming (with Python) Pietro Berkes, Brandeis University
Intro to scientific programming (with Python) Pietro Berkes, Brandeis University Next 4 lessons: Outline Scientific programming: best practices Classical learning (Hoepfield network) Probabilistic learning
Introduction to Python
WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language
CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output
CSCE 110 Programming Basics of Python: Variables, Expressions, and nput/output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Fall 2011 Python Python was developed
Visual Basic Programming. An Introduction
Visual Basic Programming An Introduction Why Visual Basic? Programming for the Windows User Interface is extremely complicated. Other Graphical User Interfaces (GUI) are no better. Visual Basic provides
How to Write a Marketing Plan: Identifying Your Market
How to Write a Marketing Plan: Identifying Your Market (Part 1 of 5) Any good marketing student will tell you that marketing consists of the four functions used to create a sale: The right product to the
Introduction to Python for Text Analysis
Introduction to Python for Text Analysis Jennifer Pan Institute for Quantitative Social Science Harvard University (Political Science Methods Workshop, February 21 2014) *Much credit to Andy Hall and Learning
JupyterHub Documentation
JupyterHub Documentation Release 0.4.0.dev Project Jupyter team January 26, 2016 User Documentation 1 Getting started with JupyterHub 3 2 Further reading 11 3 How JupyterHub works 13 4 Writing a custom
Exercise 1: Python Language Basics
Exercise 1: Python Language Basics In this exercise we will cover the basic principles of the Python language. All languages have a standard set of functionality including the ability to comment code,
Java Interview Questions and Answers
1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java
Introduction to Python
1 Daniel Lucio March 2016 Creator of Python https://en.wikipedia.org/wiki/guido_van_rossum 2 Python Timeline Implementation Started v1.0 v1.6 v2.1 v2.3 v2.5 v3.0 v3.1 v3.2 v3.4 1980 1991 1997 2004 2010
Exercise 4 Learning Python language fundamentals
Exercise 4 Learning Python language fundamentals Work with numbers Python can be used as a powerful calculator. Practicing math calculations in Python will help you not only perform these tasks, but also
Working with forms in PHP
2002-6-29 Synopsis In this tutorial, you will learn how to use forms with PHP. Page 1 Forms and PHP One of the most popular ways to make a web site interactive is the use of forms. With forms you can have
Building and breaking a Python sandbox
Building and breaking a Python sandbox Director Organizer @jessicamckellar http://jesstess.com Why? Learning a language Providing a hosted scratch pad Distributed computation Inspecting running processes
Google Drive: Access and organize your files
Google Drive: Access and organize your files Use Google Drive to store and access your files, folders, and Google Docs, Sheets, and Slides anywhere. Change a file on the web, your computer, tablet, or
CIS 192: Lecture 13 Scientific Computing and Unit Testing
CIS 192: Lecture 13 Scientific Computing and Unit Testing Lili Dworkin University of Pennsylvania Scientific Computing I Python is really popular in the scientific and statistical computing world I Why?
6.170 Tutorial 3 - Ruby Basics
6.170 Tutorial 3 - Ruby Basics Prerequisites 1. Have Ruby installed on your computer a. If you use Mac/Linux, Ruby should already be preinstalled on your machine. b. If you have a Windows Machine, you
Python Lists and Loops
WEEK THREE Python Lists and Loops You ve made it to Week 3, well done! Most programs need to keep track of a list (or collection) of things (e.g. names) at one time or another, and this week we ll show
First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science
First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca
CRASH COURSE PYTHON. Het begint met een idee
CRASH COURSE PYTHON nr. Het begint met een idee This talk Not a programming course For data analysts, who want to learn Python For optimizers, who are fed up with Matlab 2 Python Scripting language expensive
Welcome to Introduction to programming in Python
Welcome to Introduction to programming in Python Suffolk One, Ipswich, 4:30 to 6:00 Tuesday Jan 14, Jan 21, Jan 28, Feb 11 Welcome Fire exits Toilets Refreshments 1 Learning objectives of the course An
How To Make Your Database More Efficient By Virtualizing It On A Server
Virtualizing Pervasive Database Servers A White Paper From For more information, see our web site at Virtualizing Pervasive Database Servers Last Updated: 03/06/2014 As servers continue to advance in power,
Assignment 2: Option Pricing and the Black-Scholes formula The University of British Columbia Science One CS 2015-2016 Instructor: Michael Gelbart
Assignment 2: Option Pricing and the Black-Scholes formula The University of British Columbia Science One CS 2015-2016 Instructor: Michael Gelbart Overview Due Thursday, November 12th at 11:59pm Last updated
Python for Rookies. Example Examination Paper
Python for Rookies Example Examination Paper Instructions to Students: Time Allowed: 2 hours. This is Open Book Examination. All questions carry 25 marks. There are 5 questions in this exam. You should
Lab 2 : Basic File Server. Introduction
Lab 2 : Basic File Server Introduction In this lab, you will start your file system implementation by getting the following FUSE operations to work: CREATE/MKNOD, LOOKUP, and READDIR SETATTR, WRITE and
Django & Python 3. Aymeric Augustin - @aymericaugustin. PyConFR - September 16th, 2012
Django & Python 3 Aymeric Augustin - @aymericaugustin PyConFR - September 16th, 2012 1 Python 3 is the future 2 Python 3 is the future present 3 Django wants a future 4 how? 5 porting strategies 3to2 single
Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June 2014. Dr.-Ing.
Computers An Introduction to Programming with Python CCHSG Visit June 2014 Dr.-Ing. Norbert Völker Many computing devices are embedded Can you think of computers/ computing devices you may have in your
Python Basics. S.R. Doty. August 27, 2008. 1 Preliminaries 4 1.1 What is Python?... 4 1.2 Installation and documentation... 4
Python Basics S.R. Doty August 27, 2008 Contents 1 Preliminaries 4 1.1 What is Python?..................................... 4 1.2 Installation and documentation............................. 4 2 Getting
Version Control with Git. Dylan Nugent
Version Control with Git Dylan Nugent Agenda What is Version Control? (and why use it?) What is Git? (And why Git?) How Git Works (in theory) Setting up Git (surviving the CLI) The basics of Git (Just
Exercise 0. Although Python(x,y) comes already with a great variety of scientic Python packages, we might have to install additional dependencies:
Exercise 0 Deadline: None Computer Setup Windows Download Python(x,y) via http://code.google.com/p/pythonxy/wiki/downloads and install it. Make sure that before installation the installer does not complain
We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.
LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.
Software Engineering Techniques
Software Engineering Techniques Low level design issues for programming-in-the-large. Software Quality Design by contract Pre- and post conditions Class invariants Ten do Ten do nots Another type of summary
2! Multimedia Programming with! Python and SDL
2 Multimedia Programming with Python and SDL 2.1 Introduction to Python 2.2 SDL/Pygame: Multimedia/Game Frameworks for Python Literature: G. van Rossum and F. L. Drake, Jr., An Introduction to Python -
LEARNING TO PROGRAM WITH PYTHON. Richard L. Halterman
LEARNING TO PROGRAM WITH PYTHON Richard L. Halterman Copyright 2011 Richard L. Halterman. All rights reserved. i Contents 1 The Context of Software Development 1 1.1 Software............................................
The C Programming Language course syllabus associate level
TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming
Getting Started with the Internet Communications Engine
Getting Started with the Internet Communications Engine David Vriezen April 7, 2014 Contents 1 Introduction 2 2 About Ice 2 2.1 Proxies................................. 2 3 Setting Up ICE 2 4 Slices 2
Introduction to Open Atrium s workflow
Okay welcome everybody! Thanks for attending the webinar today, my name is Mike Potter and we're going to be doing a demonstration today of some really exciting new features in open atrium 2 for handling
14:440:127 Introduction to Computers for Engineers. Notes for Lecture 06
14:440:127 Introduction to Computers for Engineers Notes for Lecture 06 Rutgers University, Spring 2010 Instructor- Blase E. Ur 1 Loop Examples 1.1 Example- Sum Primes Let s say we wanted to sum all 1,
Bluefruit LE Python Library
Bluefruit LE Python Library Created by Tony DiCola Last updated on 2015-08-18 07:40:09 PM EDT Guide Contents Guide Contents Overview Hardware Installation Mac OSX Linux & Raspberry Pi Library Installation
Writing MySQL Scripts With Python's DB-API Interface
Writing MySQL Scripts With Python's DB-API Interface By Paul DuBois, NuSphere Corporation (October 2001) TABLE OF CONTENTS MySQLdb Installation A Short DB-API Script Writing the Script Running the Script
socketio Documentation
socketio Documentation Release 0.1 Miguel Grinberg January 17, 2016 Contents 1 What is Socket.IO? 3 2 Getting Started 5 3 Rooms 7 4 Responses 9 5 Callbacks 11 6 Namespaces 13 7 Using a Message Queue 15
A Simple Guide to Churn Analysis
A Simple Guide to Churn Analysis A Publication by Evergage Introduction Thank you for downloading A Simple Guide to Churn Analysis. The goal of this guide is to make analyzing churn easy, meaning you wont
Introduction. What is RAID? The Array and RAID Controller Concept. Click here to print this article. Re-Printed From SLCentral
Click here to print this article. Re-Printed From SLCentral RAID: An In-Depth Guide To RAID Technology Author: Tom Solinap Date Posted: January 24th, 2001 URL: http://www.slcentral.com/articles/01/1/raid
Computational Science and Engineering in Python
Computational Science and Engineering in Python Hans Fangohr Engineering and the Environment University of Southampton United Kingdom [email protected] September 7, 2015 1 / 355 Outline I 1 Python prompt
The programming language C. sws1 1
The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan
Format string exploitation on windows Using Immunity Debugger / Python. By Abysssec Inc WwW.Abysssec.Com
Format string exploitation on windows Using Immunity Debugger / Python By Abysssec Inc WwW.Abysssec.Com For real beneficiary this post you should have few assembly knowledge and you should know about classic
16 Collection Classes
16 Collection Classes Collections are a key feature of the ROOT system. Many, if not most, of the applications you write will use collections. If you have used parameterized C++ collections or polymorphic
Python, C++ and SWIG
Robin Dunn Software Craftsman O Reilly Open Source Convention July 21 25, 2008 Slides available at http://wxpython.org/oscon2008/ Python & C++ Comparisons Each is a general purpose programming language,
Testing Python. Applying Unit Testing, TDD, BDD and Acceptance Testing
Brochure More information from http://www.researchandmarkets.com/reports/2755225/ Testing Python. Applying Unit Testing, TDD, BDD and Acceptance Testing Description: Fundamental testing methodologies applied
Björn Bäckström, Lars Olsén and Simon Renström Copyright 2011 ClaroBet AB. Updated: May. 12, 11 You may not distribute or copy any of the text or use
Björn Bäckström, Lars Olsén and Simon Renström Copyright 2011 ClaroBet AB. Updated: May. 12, 11 You may not distribute or copy any of the text or use it in any other way except for personal use, without
CS 1133, LAB 2: FUNCTIONS AND TESTING http://www.cs.cornell.edu/courses/cs1133/2015fa/labs/lab02.pdf
CS 1133, LAB 2: FUNCTIONS AND TESTING http://www.cs.cornell.edu/courses/cs1133/2015fa/labs/lab02.pdf First Name: Last Name: NetID: The purpose of this lab is to help you to better understand functions:
Profiling, debugging and testing with Python. Jonathan Bollback, Georg Rieckh and Jose Guzman
Profiling, debugging and testing with Python Jonathan Bollback, Georg Rieckh and Jose Guzman Overview 1.- Profiling 4 Profiling: timeit 5 Profiling: exercise 6 2.- Debugging 7 Debugging: pdb 8 Debugging:
DevKey Documentation. Release 0.1. Colm O Connor
DevKey Documentation Release 0.1 Colm O Connor March 23, 2015 Contents 1 Quickstart 3 2 FAQ 5 3 Release Notes 7 i ii DevKey Documentation, Release 0.1 Github PyPI Contents 1 DevKey Documentation, Release
! Insurance and Gambling
2009-8-18 0 Insurance and Gambling Eric Hehner Gambling works as follows. You pay some money to the house. Then a random event is observed; it may be the roll of some dice, the draw of some cards, or the
Crash Course in Java
Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed Computing Netprog 2002 Java Intro 1 What is
Invitation to Ezhil : A Tamil Programming Language for Early Computer-Science Education 07/10/13
Invitation to Ezhil: A Tamil Programming Language for Early Computer-Science Education Abstract: Muthiah Annamalai, Ph.D. Boston, USA. Ezhil is a Tamil programming language with support for imperative
Using 2Can. There are three basic steps involved in migrating all of your data from your BlackBerry to your Android phone:
Using 2Can There are three basic steps involved in migrating all of your data from your BlackBerry to your Android phone: 1. Backup your BlackBerry 2. Transfer the backup file to your new Android phone
Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program
Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2015 The third
System Security Fundamentals
System Security Fundamentals Alessandro Barenghi Dipartimento di Elettronica, Informazione e Bioingegneria Politecnico di Milano alessandro.barenghi - at - polimi.it April 28, 2015 Lesson contents Overview
CIS 192: Lecture 10 Web Development with Flask
CIS 192: Lecture 10 Web Development with Flask Lili Dworkin University of Pennsylvania Last Week s Quiz req = requests.get("http://httpbin.org/get") 1. type(req.text) 2. type(req.json) 3. type(req.json())
Google Resume Search Engine Optimization (SEO) and. LinkedIn Profile Search Engine Optimization (SEO) Jonathan Duarte
Google Resume Search Engine Optimization (SEO) and LinkedIn Profile Search Engine Optimization (SEO) How to get Top 10 Rankings in Google and LinkedIn for your resume and profiles. Jonathan Duarte Http://profilelaunchpad.com
Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program
Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2014 Jill Seaman
Software Tool Seminar WS1516 - Taming the Snake
Software Tool Seminar WS1516 - Taming the Snake November 4, 2015 1 Taming the Snake 1.1 Understanding how Python works in N simple steps (with N still growing) 1.2 Step 0. What this talk is about (and
Chapter 1: Key Concepts of Programming and Software Engineering
Chapter 1: Key Concepts of Programming and Software Engineering Software Engineering Coding without a solution design increases debugging time - known fact! A team of programmers for a large software development
Practical Mac OS X Insecurity. Security Concepts, Problems and Exploits on your Mac
Practical Mac OS X Insecurity Security Concepts, Problems and Exploits on your Mac Who am I? Student of physics, mathematics and astronomy in Bonn Mac user since 1995 I love Macs Mac evangelist Intentions
qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq
qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq Introduction to Programming using Java wertyuiopasdfghjklzxcvbnmqwertyui
B&K Precision 1785B, 1786B, 1787B, 1788 Power supply Python Library
B&K Precision 1785B, 1786B, 1787B, 1788 Power supply Python Library Table of Contents Introduction 2 Prerequisites 2 Why a Library is Useful 3 Using the Library from Python 6 Conventions 6 Return values
My Secure Backup: How to reduce your backup size
My Secure Backup: How to reduce your backup size As time passes, we find our backups getting bigger and bigger, causing increased space charges. This paper takes a few Newsletter and other articles I've
>> My name is Danielle Anguiano and I am a tutor of the Writing Center which is just outside these doors within the Student Learning Center.
>> My name is Danielle Anguiano and I am a tutor of the Writing Center which is just outside these doors within the Student Learning Center. Have any of you been to the Writing Center before? A couple
Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example
Overview Elements of Programming Languages Lecture 12: Object-oriented functional programming James Cheney University of Edinburgh November 6, 2015 We ve now covered: basics of functional and imperative
B: He's getting a divorce and says he won't be able to pay for it after he pays alimony and child support.
Dialog: VIP LESSON 001 - Alimony A: Why is Kevin selling his house? B: He's getting a divorce and says he won't be able to pay for it after he pays alimony and child support. A: Why is he getting a divorce?
CS 2112 Spring 2014. 0 Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions
CS 2112 Spring 2014 Assignment 3 Data Structures and Web Filtering Due: March 4, 2014 11:59 PM Implementing spam blacklists and web filters requires matching candidate domain names and URLs very rapidly
Equity Value, Enterprise Value & Valuation Multiples: Why You Add and Subtract Different Items When Calculating Enterprise Value
Equity Value, Enterprise Value & Valuation Multiples: Why You Add and Subtract Different Items When Calculating Enterprise Value Hello and welcome to our next tutorial video here. In this lesson we're
History OOP languages Year Language 1967 Simula-67 1983 Smalltalk
History OOP languages Intro 1 Year Language reported dates vary for some languages... design Vs delievered 1957 Fortran High level programming language 1958 Lisp 1959 Cobol 1960 Algol Structured Programming
Unix Security Technologies. Pete Markowsky <peterm[at] ccs.neu.edu>
Unix Security Technologies Pete Markowsky What is this about? The goal of this CPU/SWS are: Introduce you to classic vulnerabilities Get you to understand security advisories Make
PRI-(BASIC2) Preliminary Reference Information Mod date 3. Jun. 2015
PRI-(BASIC2) Table of content Introduction...2 New Comment...2 Long variable...2 Function definition...3 Function declaration...3 Function return value...3 Keyword return inside functions...4 Function
Tutorial. Reference http://www.openflowswitch.org/foswiki/bin/view/openflow/mininetgettingstarted for more thorough Mininet walkthrough if desired
Setup Tutorial Reference http://www.openflowswitch.org/foswiki/bin/view/openflow/mininetgettingstarted for more thorough Mininet walkthrough if desired Necessary Downloads 1. Download VM at http://www.cs.princeton.edu/courses/archive/fall10/cos561/assignments/cos561tutorial.zip
Game Programming CS233G / Winter 2012 / PCC
Game Programming CS233G / Winter 2012 / PCC Portland Community College Sylvania Campus, Technology Classroom Building (TCB) room 310 Instructor: Phillip Kerman Telephone/Messages: 503-449-6701 Email: [email protected]
Computational Mathematics with Python
Computational Mathematics with Python Basics Claus Führer, Jan Erik Solem, Olivier Verdier Spring 2010 Claus Führer, Jan Erik Solem, Olivier Verdier Computational Mathematics with Python Spring 2010 1
Jenesis Software - Podcast Episode 2
Jenesis Software - Podcast Episode 2 All right, welcome to episode two with Chuck, Eddie, And Benny. And we're doing some technical talk today about network speed on episode two. Let's talk about, guys,
Introduction to Logging. Application Logging
Introduction to Logging David Beazley Copyright (C) 2008 http://www.dabeaz.com Note: This is a supplemental subject component to Dave's Python training classes. Details at: http://www.dabeaz.com/python.html
WhatsApp monitoring for Fun and Stalking. by Flavio Giobergia
WhatsApp monitoring for Fun and Stalking by Flavio Giobergia The idea behind the project If you have used WhatsApp at least once in your life, you know that there is a really lovely/shitty (deping on the
Erlang in Production. I wish I'd known that when I started Or This is nothing like the brochure :-(
Erlang in Production I wish I'd known that when I started Or This is nothing like the brochure :-( Who the Hell are you? ShoreTel Sky http://shoretelsky.com Enterprise Grade VoIP Elevator Pitch Our Systems
Introduction to Big Data with Apache Spark UC BERKELEY
Introduction to Big Data with Apache Spark UC BERKELEY This Lecture Programming Spark Resilient Distributed Datasets (RDDs) Creating an RDD Spark Transformations and Actions Spark Programming Model Python
Virtuozzo Virtualization SDK
Virtuozzo Virtualization SDK Programmer's Guide February 18, 2016 Copyright 1999-2016 Parallels IP Holdings GmbH and its affiliates. All rights reserved. Parallels IP Holdings GmbH Vordergasse 59 8200
