The document discusses properties in Python classes. Properties allow accessing attributes through normal attribute syntax, while allowing custom behavior through getter and setter methods. This avoids directly accessing attributes and allows for validation in setters. Properties are defined using the @property and @setter decorators, providing a cleaner syntax than regular getter/setter methods. They behave like regular attributes but allow underlying method calls.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 1:
- Decorators
- Descriptors
- Metaclasses
- Multiple inheritance
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
Abstract: Chances are you code in a language that's either descended from C, inspired by C, or run in an interpreter that itself is written in C. Still... do you actually know how to code in C? Despite its long-standing position as a sort of "lingua franca", an agreed-upon common language, more and more developers are putting together successful, satisfying careers, without ever learning this seminal language. But what if you have to call into C code from your favorite scripting language, or use APIs like OpenGL that are written to be called from C? Many developers find C very challenging, particularly its manual memory-management and other low-level concerns. In this session, we'll show you why you shouldn't be afraid of C, how you can use the skills you already have from the languages you code in today, and how to master structs, enums, typedefs, malloc(), free(), and the rest of C's sharp edges. Examples will be from the point-of-view of the C-skewing iPhone SDK, but will be designed to be broadly applicable and platform-agnostic.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 1:
- Decorators
- Descriptors
- Metaclasses
- Multiple inheritance
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
Abstract: Chances are you code in a language that's either descended from C, inspired by C, or run in an interpreter that itself is written in C. Still... do you actually know how to code in C? Despite its long-standing position as a sort of "lingua franca", an agreed-upon common language, more and more developers are putting together successful, satisfying careers, without ever learning this seminal language. But what if you have to call into C code from your favorite scripting language, or use APIs like OpenGL that are written to be called from C? Many developers find C very challenging, particularly its manual memory-management and other low-level concerns. In this session, we'll show you why you shouldn't be afraid of C, how you can use the skills you already have from the languages you code in today, and how to master structs, enums, typedefs, malloc(), free(), and the rest of C's sharp edges. Examples will be from the point-of-view of the C-skewing iPhone SDK, but will be designed to be broadly applicable and platform-agnostic.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 2:
- Slots vs Dictionaries
- Basic and Advanced Generators
- Async programming
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Codemotion
With TensorFlow, deep machine learning transitions from an area of research to mainstream software engineering. In this session, we'll work together to construct and train a neural network that recognises handwritten digits. Along the way, we'll discover some of the "tricks of the trade" used in neural network design, and finally, we'll bring the recognition accuracy of our model above 99%.
Не так давно вышел C# 6, основанный на новом компиляторе Roslyn. Обновление языка содержит большое количество приятных синтаксических конструкций, которые упрощают написание кода и делают его более лаконичным. Но Microsoft на этом не успокоились: прямо сейчас ведётся работа над 7-ой версией языка, которую планируют сделать ещё удобнее, благодаря реализации современных тенденций написания кода. В этом докладе мы поговорим о том, что может войти в C# 7. В числе прочего будут обсуждаться Tuples, Pattern matching, Records / algebraic data types, Nullability tracking и многое другое.
В последнее время экосистема .NET развивается очень динамично: постоянно появляются новые технологии и инструменты, а старые обзаводятся новыми возможностями. Уследить за всем очень сложно, поэтому в этом докладе мы постараемся обзорно взглянуть на текущее состояние платформы .NET, а также на то, что нас ждёт в ближайшем будущем. Будем говорить про грядущий C#7, про кроссплатформенность и нативную компиляцию, про новый .NET Core 5 и ASP.NET 5, про новые инструменты для разработчиков и последние анонсы от Microsoft.
Presentation on native interfaces for the R programming language given as part of a course in advanced R programming at FHCRC:
https://secure.bioconductor.org/SeattleMay10/
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)Tom Lee
OSDC 2010 presentation on cool stuff that can be done with Python Abstract Syntax Trees and the compile() function.
Demo Python compiler (incomplete and hacky!) can be found here: http://github.com/thomaslee/viking-poc
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 2:
- Slots vs Dictionaries
- Basic and Advanced Generators
- Async programming
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Codemotion
With TensorFlow, deep machine learning transitions from an area of research to mainstream software engineering. In this session, we'll work together to construct and train a neural network that recognises handwritten digits. Along the way, we'll discover some of the "tricks of the trade" used in neural network design, and finally, we'll bring the recognition accuracy of our model above 99%.
Не так давно вышел C# 6, основанный на новом компиляторе Roslyn. Обновление языка содержит большое количество приятных синтаксических конструкций, которые упрощают написание кода и делают его более лаконичным. Но Microsoft на этом не успокоились: прямо сейчас ведётся работа над 7-ой версией языка, которую планируют сделать ещё удобнее, благодаря реализации современных тенденций написания кода. В этом докладе мы поговорим о том, что может войти в C# 7. В числе прочего будут обсуждаться Tuples, Pattern matching, Records / algebraic data types, Nullability tracking и многое другое.
В последнее время экосистема .NET развивается очень динамично: постоянно появляются новые технологии и инструменты, а старые обзаводятся новыми возможностями. Уследить за всем очень сложно, поэтому в этом докладе мы постараемся обзорно взглянуть на текущее состояние платформы .NET, а также на то, что нас ждёт в ближайшем будущем. Будем говорить про грядущий C#7, про кроссплатформенность и нативную компиляцию, про новый .NET Core 5 и ASP.NET 5, про новые инструменты для разработчиков и последние анонсы от Microsoft.
Presentation on native interfaces for the R programming language given as part of a course in advanced R programming at FHCRC:
https://secure.bioconductor.org/SeattleMay10/
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)Tom Lee
OSDC 2010 presentation on cool stuff that can be done with Python Abstract Syntax Trees and the compile() function.
Demo Python compiler (incomplete and hacky!) can be found here: http://github.com/thomaslee/viking-poc
Object Orientation vs. Functional Programming in PythonPython Ireland
Python is a multi-paradigm language meaning it supports different programming styles, Object Orientation and Functional Programming being the major ones. However choice is not always a good thing, if you are interested in writing modular programs that are easy to maintain and promote code reuse what should you do? This talk discusses modularity in this context looking at Python's support for both paradigms, comparing and contrasting them. We then look at Python techniques and tools that bridge the perceived impedance mismatch between Object Orientation and Functional Programming.
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
This presentation takes a case-study based approach to design patterns. A purposefully simplified example of expression trees is used to explain how different design patterns can be used in practice. Examples are in C#, but is relevant for anyone who is from object oriented background.
A fast-paced introduction to Deep Learning concepts, such as activation functions, cost functions, back propagation, and then a quick dive into CNNs. Basic knowledge of vectors, matrices, and derivatives is helpful in order to derive the maximum benefit from this session. Then we'll see a short introduction to TensorFlow and TensorBoard.
An introductory-to-mid level to presentation to complex network analysis: network metrics, analysis of online social networks, approximated algorithms, memorization issues, storage.
Simple presentation on Twisted fundamentals.
Originally part 4 of a 4 lectures seminar for the Networking class of the Computer Science course at the University of Parma
Object Oriented programming in Python.
Originally part 3 of a 4 lectures seminar for the Networking class of the Computer Science course at the University of Parma
A simple introduction to the Python programming language. In Italian. OLD: superseeded by Pycrashcourse 3.1.
Originally part 1 of a 4 lectures seminar for the Networking class of the Computer Science course at the University of Parma
A simple introduction to the Python programming language. In Italian. OLD: superseeded by Pycrashcourse 3.1.
Originally presented during the Networking class of the Computer Science course at the University of Parma
Object Oriented programming in Python.
Originally part 2 of a 4 lectures seminar for the Networking class of the Computer Science course at the University of Parma
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
2. Could you please lend me the thing that you put in
2
the wall when you want to turn on the hairdryer and
the hairdryer comes from a different country?
Could you please lend me a power adapter?
3. 3
If you are out to describe the truth,
leave elegance to the tailor.
Albert Einstein
4. 4
Debugging is twice as hard as writing the
code in the first place.
Therefore, if you write the code as
cleverly as possible, you are, by definition,
not smart enough to debug it.
Brian Kernighan
6. TOC 6
Iteration
Naming
Functions are objects
Choice
Attributes and methods
Duck Typing
Exceptions [unless TimeoutError is thrown]
7. FOR vs. WHILE vs. ... 7
Iteration vs. Recursion
sys.setrecursionlimit(n)
for vs. while
Traditionally bounded iteration vs. unbounded iteration
In C for and while are completely equivalent
Some languages have for/foreach to iterate on
collections
for file in *.py; do
pygmentize -o ${file%.py}.rtf $file
done
8. Numerical Iteration 8
int i = 0; i = 0
while(i < MAX) { while i < MAX:
printf("%dn", i); print i
++i; i += 1
}
# O(n) space
for i in range(MAX):
int i = 0;
print i
for(i=0; i < MAX; ++i) {
printf("%dn", i);
# O(1) space
}
for i in xrange(MAX):
print i
9. Iteration on elements 9
It is also common to iterate
on elements of some i = 0
collection while i < len(lst):
process(lst[i]) BAD
C uses indices to iterate on i += 1
array elements
Python uses for
What if we want to iterate for el in lst:
both on elements and process(el) GOOD
indices?
10. j = 0
while j < len(lst):
process(index=j, element=lst[j]) BAD
j += 1 10
for j in range(len(lst)):
process(index=j, element=lst[j]) BAD
for j, el in enumerate(lst):
process(index=j, element=el) GOOD
11. What about Turing? 11
for is usually considered the more pythonic
alternative
Ideally every iteration should be done using for
However, we have shown only iteration on finite
collections, that is to say, for would not provide
turing-completeness
But everybody knows about generators: Python
has infinite (lazy) sequences and they cover
many other patterns as well
12. Design Implications 12
Python for statement uses external iterators, that
are extremely easy to implement through
generators
itertools provides lots of functions to
manipulate iterators
The iteration logic is pushed inside the iterator;
the client code becomes totally agnostic on how
values are generated
13. def server_socket(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(5)
csock, info = sock.accept()
return csock.makefile('rw')
13
def server(host, port):
fh = server_socket(host, port)
for i, line in enumerate(fh):
if line == "EOFrn":
break
fh.write("%4.d:t%s" % (i, line))
fh.close()
... (Forking)TCPServer and
higher level modules and frameworks are better!
14. def depth_first_visit(node):
stack = [node, ]
while stack:
current_node = stack.pop()
stack.extend(reversed(current_node.children)) 14
yield current_node.value
def breadth_first_visit(node):
queue = collections.deque((node, ))
while queue:
current_node = queue.popleft()
queue.extend(current_node.children)
yield current_node.value
for v in depth_first_visit(tree):
print v,
print
for v in breadth_first_visit(tree):
print v,
print
15. PEP-8 15
http://www.python.it/doc/articoli/pep-8.html
http://www.python.org/dev/peps/pep-0008/
‘‘‘One of Guido’s key insights is that code is read much
more often than it is written. The guidelines provided here
are intended to improve the readability of code and make
consistent across the wide spectrum of Python code. As
PEP 20 [6] says, “Readability counts”.’’’
16. PEP-8 (II) 16
Standard for source code style
names
whitespace
indentation
Consistency with this style guide is important.
Consistency within a project is more important.
Consistency within one module or function is
most important.
17. Indentation 17
4 spaces, don’t mix tabs and spaces
79 characters per line max
Wrap lines in using implied line cont. in (), [] and {}
Add parentheses to wrap lines
(not filename.startswith('.') and
filename.endswith(('.pyc', '.pyo')))
Sometimes backslash is more appropriate
Newline after operators
One blank line between functions, two between
classes
18. Space Invaders 18
Put a space after “,” [parameters, lists, tuples, etc]
Put a space after “:” in dicts, not before
Put spaces around assignments and comparisons
Unless it is an argument list
No spaces just inside parentheses or just before
argument lists
19. Naming conventions (I) 19
Always use descriptive names; the longer the
scope, the longer the name
Trailing underscore: avoids conflict with
keywords or builtins (class_)
Leading underscore: “internal use”/non-public
Double leading underscore: name mangling
Double leading and trailing: “magic”
Avoid l, 1 and similar confusing names
20. Naming conventions (II) 20
simple lower_case CamelCase ALL_CAPS
Classes X
Variables X X
Methods X X
Functions X X
Constants X
Packages X
Modules X (x)
... and self/cls first argument name for methods
21. Default values 21
The default values are evaluated once, when >>> def f(x=[]):
... x.append(1)
the function is defined and is ‘shared’ among ... return x
all call points ...
>>> f()
If the default value is a mutable object, that
[1]
leads to bugs >>> f()
>>> def g(x=None): [1, 1]
... x = [] if x is None else x >>> f()
... return x [1, 1, 1]
...
>>> g()
[]
>>> g([1, 2])
[1, 2]
22. Functions are Objects 22
In Python everything is an object
Thus, functions are objects
Functions can be passed as arguments (easy)
Functions can be returned as return values
Some APIs explicitly expect functions as arguments (sort(key=))
import sys, urllib
def reporthook(*a): print a
for url in sys.argv[1:]:
i = url.rfind('/')
file = url[i+1:]
print url, "->", file
urllib.urlretrieve(url, file, reporthook)
24. def dfs(node, pre_action=None, post_action=None):
def nop(node): pass
pre_action = pre_action or nop # bad, use if
post_action = post_action or nop # bad
stack = [] 24
def process_node(n):
def do_pre(): pre_action(n.value)
def do_post(): post_action(n.value)
def do_process():
stack.append(do_post)
for child in reversed(n.children):
stack.append(process_node(child))
stack.append(do_pre)
return do_process
stack.append(process_node(node))
while stack:
action = stack.pop()
action()
dfs(tree, pre_action=lambda x: sys.stdout.write("%s, " % x))
print
dfs(tree, post_action=lambda x: sys.stdout.write("%s, " % x))
print
25. A 1 A 11 A C E
B C 2 A C B A 12 A C E E
3 A C B 13 A C E 25
D E
4 A C B B 14 A C
Pre 5 A C B 15 A
Proc 6 A C
7 A C E D C
Post
8 A C E D
9 A C E D D
10 A C E D
26. def dfs(node, pre_action=None, post_action=None):
def nop(node): pass
pre_action = pre_action or nop
post_action = post_action or nop
stack = []
26
def process_node(n):
def do_pre(): pre_action(n.value)
def do_post(): post_action(n.value)
def do_process():
stack.append(do_post)
for child in reversed(n.children):
stack.append(process_node(child))
stack.append(do_pre)
return do_process
stack.append(process_node(node))
while stack:
action = stack.pop()
action()
Command Pattern is obsolete...
28. The case of
the missing switch 28
Some people think Python should have a switch/
case like statement, something that executes a
block of code determined by the value of a
variable
Possible solutions
Python if/elif/else statement
Seems the job for a dictionary + functions
A cleverly designed class can solve the problem as
well
29. What if we use the if? 29
An if statement is easy to read and write, if there are few
branches. Confusing if there are many branches
Theoretically correct (provided that the conditions are disjoint)
⎧ φ ( x ,…, x ) if ρ ( x ,…, x )
⎪ 1 1 n 1 1 n
⎪
f (x1 ,…, xn ) = ⎨
⎪ m( 1
φ x ,…, xn ) if ρm ( x1 ,…, xn )
⎪ φ ( x ,…, x ) otherwise
⎩ m+1 1 n
Maybe slower as conditions are evaluated in order
Some suggest that if statements should be banned ;)
30. Dictionary 30
If the body of the switch essentially sets some
(set of) variable(s), a dictionary is perfect
def some_function(n, *more_args):
# ...
masks = {
0: '0000', 1: '0001', 2: '0010', 3: '0011',
4: '0100', 5: '0101', 6: '0110', 7: '0111',
8: '1000', 9: '1001', 10: '1010', 11: '1011',
12: '1100', 13: '1101', 14: '1110', 15: '1111'
}
# ...
str_bits = masks[n]
31. Dictionary [+ Functions] 31
If the “actions” in the branches are naturally
abstracted as functions, a dictionary is perfect
import operator
# ...
class BinOp(Node):
# ...
def compute(self):
operations = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.div
}
return operations[self.op](self.left.compute(),
self.right.compute())
32. import cmd
class Example(cmd.Cmd):
def do_greet(self, rest): 32
print 'Hello %s!' % rest
def do_quit(self, rest):
return True
while 1:
words = raw_input('(cmd) ').split(' ', 1)
command = words[0]
try: rest = words[1]
except IndexError: rest=''
switch command:
case 'greet':
print 'Hello %s!' % rest
case 'quit':
break
33. 33
Properties are a neat way to implement attributes
whose usage resembles attribute access, but
whose implementation uses method calls.
These are sometimes known as “managed
attributes”.
GvR
34. Example (Track) 34
class Track(object):
def __init__(self, artist, title, duration):
self.artist = artist
self.title = title
self.duration = duration
def __str__(self):
return '%s - %s - %s' % (self.artist,
self.title,
self.duration)
35. Properties (I) 35
class A(object):
Track has public attributes def __init__(self, foo):
self._foo = foo
“Java” bad-practice
def get_foo(self):
print 'got foo'
Dependency from return self._foo
“implementation details”
def set_foo(self, val):
print 'set foo'
What if we need validation self._foo = val
in setters and such?
foo = property(get_foo, set_foo)
property: old attribute access a = A('hello')
syntax, function calls under print a.foo
# => 'got foo'
the hood # => 'hello'
a.foo = 'bar'
# => 'set foo'
36. Properties (II) 36
Sometimes we don’t need the setter...
class A(object):
def __init__(self, foo):
self._foo = foo
def get_foo(self):
print 'got foo'
return self._foo
foo = property(get_foo)
a = A('ciao')
print a.foo
# => 'got foo'
# => 'ciao'
a.foo = 'bar'
# Traceback (most recent call last):
# File "prop_example2.py", line 15, in <module>
# a.foo = 'bar'
# AttributeError: can't set attribute'
40. How Pythonic? 40
We can decouple interface from implementation
(getters/setters)
We have “read-only” attributes,
therefore, “immutable” objects
Trivial getter/setters are repetitive
Properties are helpful in order to evolve code,
but are verbose to define “immutable objects”
41. Named Tuples 41
Named Tuples solve the problem nicely
Immutable objects (easier to use, too much C++
and FP lately ☺)
Can be used both as objects and tuples
__str__ and other methods have good default
implementation
Subclassing can be used to change defaults
Very quick to write!
http://code.activestate.com/recipes/500261-named-tuples/
43. About Java/C++ types... 43
In statically typed languages like C++ we
constrain parameters to be of a given type or any
of its subtypes
However, a good programming practice is
program to an interface
Java interfaces (true dynamic polymorphism)
C++ Templates (static polymorphism)
Both solutions have problems
(however, I do love ML static typing...)
44. Books, search by title 44
If the list contains a non class Book(object):
def __init__(self, title, author):
book, an exception is self.title = title
self.author = author
raised
def find_by_title(seq, title):
Does not even work with for item in seq:
if type(item) == Book: # horrible
subclasses if item.title == title:
return item
Worst strategy else:
raise TypeError
Never type-check like def find_by_author(seq, author):
that for item in seq:
if type(item) == Book: # horrible
if item.author == author:
Solving a non-problem return item
else:
raise TypeError
45. Books, search by title 44
If the list contains a non
book, an exception is
raised
Does not even work with
subclasses
Worst strategy
Never type-check like
that
Solving a non-problem
46. Books, search by title 45
Subclasses are ok class Book(object):
def __init__(self, title, author):
self.title = title
However, code does not self.author = author
depend on elements being def find_by_title(seq, title):
books for item in seq:
if isinstance(item, Book): # bad
if item.title == title:
They have a title return item
else:
They have an author raise TypeError
What about songs? def find_by_author(seq, author):
for item in seq:
if isinstance(item, Book): # bad
Bad strategy, afterall if item.author == author:
return item
else:
raise TypeError
47. Books, search by title 45
Subclasses are ok class Song(object):
def __init__(self, title, author):
self.title = title
However, code does not self.author = author
depend on elements being def find_by_title(seq, title):
books for item in seq:
if isinstance(item, Book): # bad
if item.title == title:
They have a title return item
else:
They have an author raise TypeError
What about songs? def find_by_author(seq, author):
for item in seq:
if isinstance(item, Book): # bad
Bad strategy, afterall if item.author == author:
return item
else:
raise TypeError
48. What about movies? 46
Movies have a title. However, they have a director
and no author
find_by_title should work, find_by_author,
shouldn’t
Interface for Book e Song. And what about Movie?
Design Pattern o code duplication
Square Wheel Roads designed for square wheels
Duck typing simply avoids the problem
49. Books and Songs 47
The simplest solution is the best
class Book(object): Programmers do not code by
def __init__(self, t, a):
self.title = t
chance (hopefully)
self.author = a
AttributeErrors are raised in case
def find_by_title(seq, title):
for item in seq:
of problems
if item.title == title:
return item UnitTests discover these kind of
def find_by_author(seq, author): errors
for item in seq:
if item.author == author: You have unit tests, don’t you?
return item
50. def find_by(seq, **kwargs):
for obj in seq:
for key, val in kwargs.iteritems():
try:
if getattr(obj, key) != val:
break
48
except AttributeError:
break
else:
return obj
raise NotFound
print find_by(books, title='Python in a Nutshell')
print find_by(books, author='M. Beri')
print find_by(books, title='Python in a Nutshell',
author='A. Martelli')
try:
print find_by(books, title='Python in a Nutshell',
author='M. Beri')
print find_by(books, title='Python in a Nutshell',
pages=123)
except NotFound: pass
51. def find_by(seq, **kwargs):
for obj in seq:
for key, val in kwargs.iteritems():
try:
attr = getattr(obj, key)
except AttributeError:
break
else:
if val != attr and val not in attr:
break
else:
yield obj
52. Life expectations 50
Function parameters and every variable bound in
a function body constitutes the function local
scope
These variables scope is the whole function body
However, using them before binding is an error
53. Life expectations 50
Function parameters and every variable bound in
a function body constitutes the function local
scope
These variables scope is the whole function body
a = None
if s.startswith(t):
However, using them before binding is an error
a = s[:4]
else:
a = t
print a
WRONG
54. Life expectations 50
Function parameters and every variable bound in
a function body constitutes the function local
scope
These variables scope is the whole function body
if s.startswith(t):
However, using them before binding is an error
a = s[:4]
else:
a = t
print a
GOOD
55. LBYL vs. EAFP 51
LBYL: Look before you leap # LBYL -- bad
if id_ in employees:
EAFP: Easier to ask emp = employees[id_]
forgiveness than permission else:
report_error(...)
Usually EAFP is the best
strategy
Exception are rather fast #EAFP -- good
try:
Atomicity, ... emp = employees[id_]
except KeyError:
report_error(...)
56. if os.access(filename, os.F_OK):
fh = file(filename)
else: BAD
print "Something went bad." 52
if os.access(filename, os.F_OK):
try:
fh = file(filename)
except IOError: VERBOSE
print "Something went bad."
else:
print "Something went bad."
try:
fh = file(filename)
except IOError: GOOD
print "Something went bad."
57. More on Exceptions 53
Exceptions should subclass Exception directly or
indirectly
Catch exceptions using the most specific
specifier
Don’t use the base except: unless
You plan to re-raise the exception (but you
probably should use finally)
You want to log any error or something like that
Also catches KeyboardInterrupt
58. Limit the try scope 54
try:
# Too broad! BAD
return handle_value(collection[key])
except KeyError:
# Will also catch KeyError raised by handle_value()
return key_not_found(key)
try: GOOD
value = collection[key]
except KeyError:
return key_not_found(key)
else:
return handle_value(value)
59. References 55
Python in a Nutshell, 2ed, Alex Martelli, O’Reilly
Python Cookbook, Alex Martelli, Anna Martelli
Ravenscroft and David Ascher, O’Reilly
Agile Software Development: Principles, Patterns and
Practices, Robert C. Martin, Prentice Hall
Code Clean, Robert C. Martin, Prentice Hall
Structure and Interpretation of Computer Programs,
H. Abelson, G. Sussman, J. Sussman,
http://mitpress.mit.edu/sicp/full-text/book/book.html