SlideShare a Scribd company logo
1 of 24
Download to read offline
from java to python
beating the stockholm syndrome
Javier Arias Losada
@javier_arilos
We are going to compare Java versus Python
through some random topics… but not trying to
be exhaustive or follow any logical patterns…
just aspects I liked, disliked or just caught my
attention.
Disclaimer
1. Some points have been improved in latest versions of Python
and Java
2. Opinions stated are those of the author, Javier Arias
Working since 1997 with OO languages, mainly in
Java and some Smalltalk… one has some rigidness
regarding idioms, mental schemes and patterns…
Python approach to many aspects is different
from Java and tends to be more pragmatic.
verbosity and ease of reading (I)
“(…) when you program, you have to think about how someone will read your
code, not just how a computer will interpret it.”
- Kent Beck
Indentation, expressiveness and idioms, libraries matter.
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// do something with line.
}
br.close();
with open(...) as f:
for line in f:
# do something with line
http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-in-java
http://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python
verbosity and ease of reading (II)
logical expressions & truthy values:
if x and x not in elements:
print ‘done’

if (x != null && !elements.contains(x))
{
System.out.println(“done”);
}
Python seems to be ahead here, improves this productivity?
Usually code is easier to read and maintain in Python.
Refactoring is faster and more secure in Java (static typing
+ advanced IDE’s).
verbosity and ease of reading (III)
method and function definition
An example: parse N lines of a file, searching for a text
Python keyword args: named and optional, default values.
def search(txt, file=’./f.txt’, lines=0):
return 0
Java method overriding: different methods with different
parameters (number and type)
public int search(String txt, String file, Integer lines){
return 0;
}
verbosity and ease of reading (IV)
Lets add optional params in Java:
public int search(String txt, Integer lines){
search(txt, “./f.txt”, lines);
}
public int search(String txt, String file){
search(txt, file, 0);
}
Java’s method signature overriding is very useful for
maintaining functions (and constructors) less cluttered.
verbosity and ease of reading (V)
New Requirement: extend our search function to search for a
client’s name, accept instances of Client class.
public int search(Client client, String file){
search(client.getName(), file);
}
def search(what, file=’./f.txt’, lines=0):
if isinstance(what, Client):
what = what.name
(...)
Results of the exercise:
Java: one core method and three “facilitator” methods.
Python: one method that is caring about type of parameters.
verbosity and ease of reading (VI)
List and dictionary comprehensions
a real example: filtering a dictionary.
filtered_policies = {pol: spr_message.policies[pol]
for pol in _GCM_ALLOWED_POLICIES
if pol in spr_message.policies}
Python Dict and list comprehension are very flexible and
powerful ways of creating lists and dict on the fly.
filteredPolicies = sprMessage.getPolicies().keySet()
.retainAll(GCM_ALLOWED_POLICIES);
Java is usually more verbose and less fluent for this
collection related tasks, but sometimes a well designed API
can do miracles, as in this example.
verbosity and ease of reading (end)
searched google looking for
the shortest tutorials of each language:
As an objective indicator,

Teach yourself Java in 21 minutes:
http://www.debevc.uni-mb.si/IT2003/Razno/teach_Java_21_minutes.pdf

Learn Python in 10 minutes:
http://www.stavros.io/tutorials/python/

Python is half as verbose as Java.
If you ignore me, in the time of this talk you can learn both
languages.
Just joking :-)
as object oriented languages (I)
inheritance
Liskov Substitution Principle: If S is a subtype of T, then
objects of type T may be replaced with objects of type S.
Use your code without caring about what type or subtype it is.

Java
simple inheritance.
interfaces.
statically-strongly typed.

Python
multiple inheritance.
dynamically-strongly typed.
as object oriented languages (II)
composition-inheritance-multiple inheritance
“In object-oriented programming, Inheritance is the evil forest (...) deep inside
the Dark Forest Inheritance is the Evil Queen Multiple Inheritance (...)”
- Learn Python the hard way:

http://bit.ly/O709e9

Java super
super();
super.aMethod();

Python super
super(class, object)
super may not call parent: MRO
A
/

super always call parent.



B

C



/
D

About MRO in Python: http://bit.ly/18RHQBC
as object oriented languages (III)
inheritance
The Circle / Ellipse problem:
➔ In maths, circle is a special case for an ellipse: both axes
are equal
➔ Who should be superclass and subclass?
◆
◆

If Ellipse is the parent: what happens with the Ellipse method that
stretches an axis? what does that mean for Circle instances?
If Circle is the parent, seems counterintuitive and no code reused.

Two ways of thinking about subclassing:
1.
2.

The OO classic view
Pragmatic’s non-taxonomy based approach
as object oriented languages (IV)
inheritance, classic OO view
a subclass is a specialization of a superclass.
Organize your code by taxonomies: "Is-a" relationships. e.g. Dog
is-an Animal.
"Inheritance is the idea that one class is a specialization of another class." Code Complete.

This is what the majority of us do: at least in Java, probably
in Python as well.
as object oriented languages (V)
inheritance, alternative approach
Inheritance as a mechanism for code reuse,
nothing to do with taxonomies.
Raymond Hettinger, Python core developer:

Put the Dog on top,
if the Dog has more code that is useful for Animal

From The art of subclassing, Raymond Hettinger.
"How do you decide which one is on top? There is no principle of specialization. (...) Why do we
subclass? Is just a way to reuse code. (...) the one that has more code that is reusable by the other
class should be the parent. If the Dog has more code that is useful for Animal, put the Dog on top.”
http://www.youtube.com/watch?feature=player_detailpage&v=miGolgp9xq8#t=640
as object oriented languages (VI)
polymorphism

[1]

- ad-hoc polymorphism: function overloading [already covered]
- parametric polymorphism: generic type that can handle
different types without worrying about their types.
Java: generics:
List<String> l = new ArrayList<String>();
Python: builtin:
l = []

[1]three types of polymorphism, according to wikipedia http://en.wikipedia.
org/wiki/Polymorphism_(computer_science)
as object oriented languages (VII)
polymorphism
- subtyping polymorphism: duck and chicken walk differently

Java: inheritance + interfaces + static typing
public class Duck extends Bird implements Swimmer{
public String quack(){

(...)

public void walk(){

(...)

(...)

Duck donald = new Duck();
donald.walk();
donald.fly();
donald.quack();
donald.swim();
[1]three types of polymorphism, according to wikipedia http://en.wikipedia.
org/wiki/Polymorphism_(computer_science)
as object oriented languages (VII)
polymorphism
- subtyping polymorphism: duck and chicken walk differently

Python: inheritance + duck typing + protocols
class Duck(Bird):
def quack():
def walk():

(...)
(...)

(...)

donald = Duck()
donald.walk()
donald.fly()
donald.quack()
donald.swim()
[1]three types of polymorphism, according to wikipedia http://en.wikipedia.
org/wiki/Polymorphism_(computer_science)
as object oriented languages (VII)
encapsulation:
OCP (open closed principle) : "software entities (classes, modules,
functions, etc.) should be open for extension, but closed for modification"
http://en.wikipedia.org/wiki/Open/closed_principle

visibility (public, protected, ...), javabeans (Java)
versus
"_", "we are all consenting adults here" (Python)

[1]

Python name mangling.
[1] from python mail: https://mail.python.org/pipermail/tutor/2003-October/025932.
html
execution model (I)
Python execution model differs from those of Java and C++.

In Python everything is a name bounded to an object.
In Java class lifecycle is
separated in load,
initialization and execution.

In Python, LoC are executed.
No separation between
declaration and execution.

1. Class resolved and loaded.
2. Class is initialized.
3. Code in class used.

Functions (def)
(class)

Modules
Entry points to code well
defined: main

Classes

(import)

Entry points to code are the
same modules
execution model (III)

●

Diferenciate explicit execution from import time execution?

if __name__ == ‘_main__’:
“””your program here”””
execution model (III)
●
●
●

implicit variable declaration
duplicate declarations
parameter default values that are mutable

class A(object):
def __init__(self, p1=0,
p2=None,p3=[]):
self.v1 = p1
self.v2 = p2
self.v3 = p3
def method1(self, p):
self.v3.append(p)
def method1(self, p1, p2):
self.lastp1 = p1
self.v3.append(p2)
print self.lastp1

In [5]: a = A(p2=3)
In [6]: a.method1(1, 2)
1
In [9]: print a.lastp1
1
In [10]: a2 = A(p1=3)
In [12]: print a2.v3
[2]
In [13]: print a.v3
[2]
execution model (IV)
monkey patching
class A(object):
def __init__(self, p1=0,
p2=None,p3=[]):
self.v1 = p1
self.v2 = p2
self.v3 = p3
def method1(self, p):
self.v3.append(p)
def method1(self, p1, p2):
self.lastp1 = p1
self.v3.append(p2)
print self.lastp1

In [22]: a = A()
In [23]: a.method1(1, 2)
1
In [24]: def m1(self, p, p2):
print 'modified ' + str
(p)
....:
In [25]: A.method1 = m1
In [26]: a.method1(1, 2)
modified 1

Remember: in Python everything is a name bounded to an object.
wrap up

You solve the problems.
The most important part of
any language is you, the
developer.
No clear winner, today I
prefer Python.

Thanks for attending!

More Related Content

What's hot

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programmingSrinivas Narasegouda
 
Introduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsIntroduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsPhoenix
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1Kirti Verma
 
Python Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and PolymorphismPython Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and PolymorphismRanel Padon
 
Python-00 | Introduction and installing
Python-00 | Introduction and installingPython-00 | Introduction and installing
Python-00 | Introduction and installingMohd Sajjad
 
A Featherweight Approach to FOOL
A Featherweight Approach to FOOLA Featherweight Approach to FOOL
A Featherweight Approach to FOOLgreenwop
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
C++0x :: Introduction to some amazing features
C++0x :: Introduction to some amazing featuresC++0x :: Introduction to some amazing features
C++0x :: Introduction to some amazing featuresChristian Perone
 
Introduction to python 3
Introduction to python 3Introduction to python 3
Introduction to python 3Youhei Sakurai
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objectsrahulsahay19
 
Introduction to python 3 2nd round
Introduction to python 3   2nd roundIntroduction to python 3   2nd round
Introduction to python 3 2nd roundYouhei Sakurai
 
Introduction about Python by JanBask Training
Introduction about Python by JanBask TrainingIntroduction about Python by JanBask Training
Introduction about Python by JanBask TrainingJanBask Training
 

What's hot (20)

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python ppt
Python pptPython ppt
Python ppt
 
Python Tutorial for Beginner
Python Tutorial for BeginnerPython Tutorial for Beginner
Python Tutorial for Beginner
 
Introduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsIntroduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data Analytics
 
Oop basic concepts
Oop basic conceptsOop basic concepts
Oop basic concepts
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1
 
Python Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and PolymorphismPython Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and Polymorphism
 
Python-00 | Introduction and installing
Python-00 | Introduction and installingPython-00 | Introduction and installing
Python-00 | Introduction and installing
 
Basics of python
Basics of pythonBasics of python
Basics of python
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
A Featherweight Approach to FOOL
A Featherweight Approach to FOOLA Featherweight Approach to FOOL
A Featherweight Approach to FOOL
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
C++0x :: Introduction to some amazing features
C++0x :: Introduction to some amazing featuresC++0x :: Introduction to some amazing features
C++0x :: Introduction to some amazing features
 
Python - Lesson 1
Python - Lesson 1Python - Lesson 1
Python - Lesson 1
 
Introduction to python 3
Introduction to python 3Introduction to python 3
Introduction to python 3
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
 
Introduction to python 3 2nd round
Introduction to python 3   2nd roundIntroduction to python 3   2nd round
Introduction to python 3 2nd round
 
Introduction about Python by JanBask Training
Introduction about Python by JanBask TrainingIntroduction about Python by JanBask Training
Introduction about Python by JanBask Training
 
Oop
OopOop
Oop
 

Viewers also liked

Jython: Integrating Python and Java
Jython: Integrating Python and JavaJython: Integrating Python and Java
Jython: Integrating Python and JavaCharles Anderson
 
Ruby vs python
Ruby vs pythonRuby vs python
Ruby vs pythonIgor Leroy
 
Closing the gap between Distros(devs) and their Users(ops)
Closing the gap between Distros(devs) and their Users(ops)Closing the gap between Distros(devs) and their Users(ops)
Closing the gap between Distros(devs) and their Users(ops)Kris Buytaert
 
Dev secops opsec, devsec, devops ?
Dev secops opsec, devsec, devops ?Dev secops opsec, devsec, devops ?
Dev secops opsec, devsec, devops ?Kris Buytaert
 

Viewers also liked (7)

Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
Jython: Integrating Python and Java
Jython: Integrating Python and JavaJython: Integrating Python and Java
Jython: Integrating Python and Java
 
Ruby vs python
Ruby vs pythonRuby vs python
Ruby vs python
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
Closing the gap between Distros(devs) and their Users(ops)
Closing the gap between Distros(devs) and their Users(ops)Closing the gap between Distros(devs) and their Users(ops)
Closing the gap between Distros(devs) and their Users(ops)
 
Dev secops opsec, devsec, devops ?
Dev secops opsec, devsec, devops ?Dev secops opsec, devsec, devops ?
Dev secops opsec, devsec, devops ?
 
Mixing Python and Java
Mixing Python and JavaMixing Python and Java
Mixing Python and Java
 

Similar to From Java to Python: beating the Stockholm syndrome

These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2sadhana312471
 
PRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxPRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxabhishek364864
 
Interview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfInterview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfExaminationSectionMR
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxRohitKumar639388
 
Pursuing Domain-Driven Design practices in PHP
Pursuing Domain-Driven Design practices in PHPPursuing Domain-Driven Design practices in PHP
Pursuing Domain-Driven Design practices in PHPGiorgio Sironi
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| FundamentalsMohd Sajjad
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptxVijalJain3
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming LanguageYLTO
 
PythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programmingPythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programmingKhadijaKhadijaAouadi
 

Similar to From Java to Python: beating the Stockholm syndrome (20)

These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
PRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxPRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptx
 
Oop java
Oop javaOop java
Oop java
 
Python for dummies
Python for dummiesPython for dummies
Python for dummies
 
Interview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfInterview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdf
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Python training
Python trainingPython training
Python training
 
Pursuing Domain-Driven Design practices in PHP
Pursuing Domain-Driven Design practices in PHPPursuing Domain-Driven Design practices in PHP
Pursuing Domain-Driven Design practices in PHP
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Python
PythonPython
Python
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Core java part1
Core java  part1Core java  part1
Core java part1
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming Language
 
PYTHON PPT.pptx
PYTHON PPT.pptxPYTHON PPT.pptx
PYTHON PPT.pptx
 
обзор Python
обзор Pythonобзор Python
обзор Python
 
PythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programmingPythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programming
 

More from Javier Arias Losada

Why do lazy developers write beautiful code?
Why do lazy developers write beautiful code?Why do lazy developers write beautiful code?
Why do lazy developers write beautiful code?Javier Arias Losada
 
Europython - Machine Learning for dummies with Python
Europython - Machine Learning for dummies with PythonEuropython - Machine Learning for dummies with Python
Europython - Machine Learning for dummies with PythonJavier Arias Losada
 
Pybcn machine learning for dummies with python
Pybcn machine learning for dummies with pythonPybcn machine learning for dummies with python
Pybcn machine learning for dummies with pythonJavier Arias Losada
 
OSCON - ES6 metaprogramming unleashed
OSCON -  ES6 metaprogramming unleashedOSCON -  ES6 metaprogramming unleashed
OSCON - ES6 metaprogramming unleashedJavier Arias Losada
 
Elastically scalable architectures with microservices. The end of the monolith?
Elastically scalable architectures with microservices. The end of the monolith?Elastically scalable architectures with microservices. The end of the monolith?
Elastically scalable architectures with microservices. The end of the monolith?Javier Arias Losada
 
Full Stack Bus with Javascript, RabbitMQ and Postal.js
Full Stack Bus with Javascript, RabbitMQ and Postal.jsFull Stack Bus with Javascript, RabbitMQ and Postal.js
Full Stack Bus with Javascript, RabbitMQ and Postal.jsJavier Arias Losada
 
Rabbitmq, amqp Intro - Messaging Patterns
Rabbitmq, amqp Intro - Messaging PatternsRabbitmq, amqp Intro - Messaging Patterns
Rabbitmq, amqp Intro - Messaging PatternsJavier Arias Losada
 
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel Messaging
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel MessagingNoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel Messaging
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel MessagingJavier Arias Losada
 

More from Javier Arias Losada (9)

Why do lazy developers write beautiful code?
Why do lazy developers write beautiful code?Why do lazy developers write beautiful code?
Why do lazy developers write beautiful code?
 
Europython - Machine Learning for dummies with Python
Europython - Machine Learning for dummies with PythonEuropython - Machine Learning for dummies with Python
Europython - Machine Learning for dummies with Python
 
Pybcn machine learning for dummies with python
Pybcn machine learning for dummies with pythonPybcn machine learning for dummies with python
Pybcn machine learning for dummies with python
 
OSCON - ES6 metaprogramming unleashed
OSCON -  ES6 metaprogramming unleashedOSCON -  ES6 metaprogramming unleashed
OSCON - ES6 metaprogramming unleashed
 
ES6 metaprogramming unleashed
ES6 metaprogramming unleashedES6 metaprogramming unleashed
ES6 metaprogramming unleashed
 
Elastically scalable architectures with microservices. The end of the monolith?
Elastically scalable architectures with microservices. The end of the monolith?Elastically scalable architectures with microservices. The end of the monolith?
Elastically scalable architectures with microservices. The end of the monolith?
 
Full Stack Bus with Javascript, RabbitMQ and Postal.js
Full Stack Bus with Javascript, RabbitMQ and Postal.jsFull Stack Bus with Javascript, RabbitMQ and Postal.js
Full Stack Bus with Javascript, RabbitMQ and Postal.js
 
Rabbitmq, amqp Intro - Messaging Patterns
Rabbitmq, amqp Intro - Messaging PatternsRabbitmq, amqp Intro - Messaging Patterns
Rabbitmq, amqp Intro - Messaging Patterns
 
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel Messaging
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel MessagingNoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel Messaging
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel Messaging
 

Recently uploaded

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

From Java to Python: beating the Stockholm syndrome

  • 1. from java to python beating the stockholm syndrome Javier Arias Losada @javier_arilos
  • 2. We are going to compare Java versus Python through some random topics… but not trying to be exhaustive or follow any logical patterns… just aspects I liked, disliked or just caught my attention. Disclaimer 1. Some points have been improved in latest versions of Python and Java 2. Opinions stated are those of the author, Javier Arias
  • 3. Working since 1997 with OO languages, mainly in Java and some Smalltalk… one has some rigidness regarding idioms, mental schemes and patterns… Python approach to many aspects is different from Java and tends to be more pragmatic.
  • 4. verbosity and ease of reading (I) “(…) when you program, you have to think about how someone will read your code, not just how a computer will interpret it.” - Kent Beck Indentation, expressiveness and idioms, libraries matter. BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { // do something with line. } br.close(); with open(...) as f: for line in f: # do something with line http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-in-java http://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python
  • 5. verbosity and ease of reading (II) logical expressions & truthy values: if x and x not in elements: print ‘done’ if (x != null && !elements.contains(x)) { System.out.println(“done”); } Python seems to be ahead here, improves this productivity? Usually code is easier to read and maintain in Python. Refactoring is faster and more secure in Java (static typing + advanced IDE’s).
  • 6. verbosity and ease of reading (III) method and function definition An example: parse N lines of a file, searching for a text Python keyword args: named and optional, default values. def search(txt, file=’./f.txt’, lines=0): return 0 Java method overriding: different methods with different parameters (number and type) public int search(String txt, String file, Integer lines){ return 0; }
  • 7. verbosity and ease of reading (IV) Lets add optional params in Java: public int search(String txt, Integer lines){ search(txt, “./f.txt”, lines); } public int search(String txt, String file){ search(txt, file, 0); } Java’s method signature overriding is very useful for maintaining functions (and constructors) less cluttered.
  • 8. verbosity and ease of reading (V) New Requirement: extend our search function to search for a client’s name, accept instances of Client class. public int search(Client client, String file){ search(client.getName(), file); } def search(what, file=’./f.txt’, lines=0): if isinstance(what, Client): what = what.name (...) Results of the exercise: Java: one core method and three “facilitator” methods. Python: one method that is caring about type of parameters.
  • 9. verbosity and ease of reading (VI) List and dictionary comprehensions a real example: filtering a dictionary. filtered_policies = {pol: spr_message.policies[pol] for pol in _GCM_ALLOWED_POLICIES if pol in spr_message.policies} Python Dict and list comprehension are very flexible and powerful ways of creating lists and dict on the fly. filteredPolicies = sprMessage.getPolicies().keySet() .retainAll(GCM_ALLOWED_POLICIES); Java is usually more verbose and less fluent for this collection related tasks, but sometimes a well designed API can do miracles, as in this example.
  • 10. verbosity and ease of reading (end) searched google looking for the shortest tutorials of each language: As an objective indicator, Teach yourself Java in 21 minutes: http://www.debevc.uni-mb.si/IT2003/Razno/teach_Java_21_minutes.pdf Learn Python in 10 minutes: http://www.stavros.io/tutorials/python/ Python is half as verbose as Java. If you ignore me, in the time of this talk you can learn both languages. Just joking :-)
  • 11. as object oriented languages (I) inheritance Liskov Substitution Principle: If S is a subtype of T, then objects of type T may be replaced with objects of type S. Use your code without caring about what type or subtype it is. Java simple inheritance. interfaces. statically-strongly typed. Python multiple inheritance. dynamically-strongly typed.
  • 12. as object oriented languages (II) composition-inheritance-multiple inheritance “In object-oriented programming, Inheritance is the evil forest (...) deep inside the Dark Forest Inheritance is the Evil Queen Multiple Inheritance (...)” - Learn Python the hard way: http://bit.ly/O709e9 Java super super(); super.aMethod(); Python super super(class, object) super may not call parent: MRO A / super always call parent. B C / D About MRO in Python: http://bit.ly/18RHQBC
  • 13. as object oriented languages (III) inheritance The Circle / Ellipse problem: ➔ In maths, circle is a special case for an ellipse: both axes are equal ➔ Who should be superclass and subclass? ◆ ◆ If Ellipse is the parent: what happens with the Ellipse method that stretches an axis? what does that mean for Circle instances? If Circle is the parent, seems counterintuitive and no code reused. Two ways of thinking about subclassing: 1. 2. The OO classic view Pragmatic’s non-taxonomy based approach
  • 14. as object oriented languages (IV) inheritance, classic OO view a subclass is a specialization of a superclass. Organize your code by taxonomies: "Is-a" relationships. e.g. Dog is-an Animal. "Inheritance is the idea that one class is a specialization of another class." Code Complete. This is what the majority of us do: at least in Java, probably in Python as well.
  • 15. as object oriented languages (V) inheritance, alternative approach Inheritance as a mechanism for code reuse, nothing to do with taxonomies. Raymond Hettinger, Python core developer: Put the Dog on top, if the Dog has more code that is useful for Animal From The art of subclassing, Raymond Hettinger. "How do you decide which one is on top? There is no principle of specialization. (...) Why do we subclass? Is just a way to reuse code. (...) the one that has more code that is reusable by the other class should be the parent. If the Dog has more code that is useful for Animal, put the Dog on top.” http://www.youtube.com/watch?feature=player_detailpage&v=miGolgp9xq8#t=640
  • 16. as object oriented languages (VI) polymorphism [1] - ad-hoc polymorphism: function overloading [already covered] - parametric polymorphism: generic type that can handle different types without worrying about their types. Java: generics: List<String> l = new ArrayList<String>(); Python: builtin: l = [] [1]three types of polymorphism, according to wikipedia http://en.wikipedia. org/wiki/Polymorphism_(computer_science)
  • 17. as object oriented languages (VII) polymorphism - subtyping polymorphism: duck and chicken walk differently Java: inheritance + interfaces + static typing public class Duck extends Bird implements Swimmer{ public String quack(){ (...) public void walk(){ (...) (...) Duck donald = new Duck(); donald.walk(); donald.fly(); donald.quack(); donald.swim(); [1]three types of polymorphism, according to wikipedia http://en.wikipedia. org/wiki/Polymorphism_(computer_science)
  • 18. as object oriented languages (VII) polymorphism - subtyping polymorphism: duck and chicken walk differently Python: inheritance + duck typing + protocols class Duck(Bird): def quack(): def walk(): (...) (...) (...) donald = Duck() donald.walk() donald.fly() donald.quack() donald.swim() [1]three types of polymorphism, according to wikipedia http://en.wikipedia. org/wiki/Polymorphism_(computer_science)
  • 19. as object oriented languages (VII) encapsulation: OCP (open closed principle) : "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification" http://en.wikipedia.org/wiki/Open/closed_principle visibility (public, protected, ...), javabeans (Java) versus "_", "we are all consenting adults here" (Python) [1] Python name mangling. [1] from python mail: https://mail.python.org/pipermail/tutor/2003-October/025932. html
  • 20. execution model (I) Python execution model differs from those of Java and C++. In Python everything is a name bounded to an object. In Java class lifecycle is separated in load, initialization and execution. In Python, LoC are executed. No separation between declaration and execution. 1. Class resolved and loaded. 2. Class is initialized. 3. Code in class used. Functions (def) (class) Modules Entry points to code well defined: main Classes (import) Entry points to code are the same modules
  • 21. execution model (III) ● Diferenciate explicit execution from import time execution? if __name__ == ‘_main__’: “””your program here”””
  • 22. execution model (III) ● ● ● implicit variable declaration duplicate declarations parameter default values that are mutable class A(object): def __init__(self, p1=0, p2=None,p3=[]): self.v1 = p1 self.v2 = p2 self.v3 = p3 def method1(self, p): self.v3.append(p) def method1(self, p1, p2): self.lastp1 = p1 self.v3.append(p2) print self.lastp1 In [5]: a = A(p2=3) In [6]: a.method1(1, 2) 1 In [9]: print a.lastp1 1 In [10]: a2 = A(p1=3) In [12]: print a2.v3 [2] In [13]: print a.v3 [2]
  • 23. execution model (IV) monkey patching class A(object): def __init__(self, p1=0, p2=None,p3=[]): self.v1 = p1 self.v2 = p2 self.v3 = p3 def method1(self, p): self.v3.append(p) def method1(self, p1, p2): self.lastp1 = p1 self.v3.append(p2) print self.lastp1 In [22]: a = A() In [23]: a.method1(1, 2) 1 In [24]: def m1(self, p, p2): print 'modified ' + str (p) ....: In [25]: A.method1 = m1 In [26]: a.method1(1, 2) modified 1 Remember: in Python everything is a name bounded to an object.
  • 24. wrap up You solve the problems. The most important part of any language is you, the developer. No clear winner, today I prefer Python. Thanks for attending!