dynamic language programming for the statically typed programmer
DESCRIPTION
Un programmatore di C# (statically typed language) che usa un Dynamic Language http://codeisvalue.wordpress.com/2010/01/23/post-ugi-alt-net-conference/TRANSCRIPT
Beyond .NET
Dynamic Language Programmingfor the Statically Typed Programmer
M a r c o P a r e n z a n
Beyond .NET?
• Bisogna essere più precisi
– Beyond statically typed (“traditional”, “original”) .NET
– Ma .NET è sempre lì
– “Dynamic” è qualcosa in più
2
M a r c o P a r e n z a n
Confronto
StaticLanguages
Robusto
Performante
Strumenti“intelligenti”
Migliore scalabilità
DynamicLanguages
Semplice e stringato
Interpretato(no compilazione)
“implicitamentetipizzato”
Meta-programming
3
M a r c o P a r e n z a n
Le peculiarità di un Dynamic Language
• Semplice e stringato– È una scelta tipica di chi ha sviluppato questi linguaggi– Sintassi leggera– Molte funzioni lasciate in API in linguaggi statici sono
implementate nel linguaggio
• Interpretato– È la diretta conseguenza della semplicità, evitando la
“complicazione” di un processo di compilazione
• Implicitamente tipizzato– Il tipo è associato ai valori, non alle variabili– Non permettono di verificare e notificare gli errori di tipo
se non quando vanno in esecuzione
4
M a r c o P a r e n z a n
Metaprogramming
• Il metaprogramming è la scrittura di un programma in grado di scrivere o manipolare altri programmi o se stesso
• Un metaprogramma effettua a tempo di esecuzioni operazioni che sarebbero, in condizioni normali, effettuate a tempo di compilazione
• L'obiettivo del metaprogramming è quello di produrre programmi in grado di adattarsi dinamicamente ad una configurazione che cambia nel tempo, senza intervento umano
5www.xedotnet.org
M a r c o P a r e n z a n
Alune definizioni
• Metaprogramma: il prodotto dell'atto di metaprogramming
• Metalinguaggio: linguaggio utilizzato per scrivere il metaprogramma
• Se il metalinguaggio ed il linguaggio di programmazione coincidono, l'attività di metaprogramming prende il nome di reflection
6www.xedotnet.org
M a r c o P a r e n z a n
Quale scegliere?
• Due “generazioni” di linguaggi– Nativi (con virtual machine proprietaria)– Su Runtime (.NET o JVM)
• Alcuni– Python (IronPython, Jython)– Ruby (IronRuby, JRuby)
• Perché portare Python o Ruby su .NET o JVM?– Py o Rb usano il runtime– Py o Rb sono accessibli dal runtime (e questo è il
nostro caso)
7
M a r c o P a r e n z a n
Cos’è Python?
• Un linguaggio di programmazione general purpose• Sviluppato da Guido van Rossum nel 1991• Un linguaggio dinamico usato spesso come linguaggio di scripting• Supporta diversi paradigmi di programmazione:
– Object Oriented– Imperative– Functional
• È stato creato con questi obiettivi in mente:– Leggibilità del codice– Sintassi minimalista– Un esteso set di librerie– Duck Typing
9
M a r c o P a r e n z a n
Cos’è IronPython?
• È una implementazione del linguaggio Python su piattaforma .NET– IronPython è scritto interamente in C#
• Creato da Jim Hugunin– sviluppatore anche di Jython (Python su JVM)
• Voleva scrivere un paper dal titolo “Why .NET is a Terrible Platform for Dynamic Languages”– “It was a little less than a year ago that I first started investigating the Common
Language Runtime (CLR). My plan was to do a little work and then write a short pithy article called, "Why .NET is a terrible platform for dynamic languages”" http://www.ironpython.com/old.html
• Nel settembre del 2004 iniziava a lavorare in Microsoft– “My plans changed when I found the CLR to be an excellent target for the highly dynamic
Python language. Since then I've spent much of my spare time working on the development of IronPython” http://www.ironpython.com/old.html
– http://www.python.org/community/pycon/dc2004/papers/9/– http://conferences.oreillynet.com/presentations/os2004/hugunin_jim_up.ppt
10
M a r c o P a r e n z a n
IronPython Performances (2004)Test Descrizione Prestazione
parser (b0) heavy OO plus meta programming x1.1 faster
stacks (b1) handling of stack overflow x2.1 faster
PI (b2) using generators to compute π same
sorting (b3) many different comparsions and sorting x1.5 faster
parser2 (b4) reprise of parser with different input x1.2 slower
builtins (b5) testing unicode, complex numbers, … x2.3 slower
iterators (b6) – looping and overflow from int to long x1.2 faster
11
0 1 2 3 4 5 6 7 8 9 10 11 12
Python-2.3
IronPython
IronPython (Mono)
time (seconds)
b0 b1 b2 b3 b4 b5 b6
OSCon 2004 – IronPython 0.61.7x faster than Python-2.3 on
pystone
M a r c o P a r e n z a n
Performances (2009)
• Performance Comparisons– http://ironpython.codeplex.com/wikipage
?title=IronPython%20Performance
• IronPython 2.6 Final– http://ironpython.codeplex.com/wikipage
?title=IP26FinalVsCPy26Perf&referringTitle=IronPython%20Performance
Test CPy2.6.1 IPy2.6
Hello World 0.0655611s 2.1076478s
PyStone 1.1 39239.6pys/s 55765.7 pys/s
Richards 611.8 1400.05
12
M a r c o P a r e n z a n
Performances (2009)PyBench 2.0
Test IPy2.6 CPy2.6.1 Δ
BuiltinFunctionCalls: 403ms 1737ms -76.8%
BuiltinMethodLookup: 606ms 1835ms -67.0%
CompareFloats: 28ms 1075ms -97.4%
CompareFloatsIntegers: 403ms 1354ms -70.2%
CompareIntegers: 27ms 853ms -96.9%
CompareInternedStrings: 395ms 1237ms -68.1%
CompareLongs: 29ms 1071ms -97.3%
CompareStrings: 477ms 1428ms -66.6%
CompareUnicode: 400ms 1188ms -66.3%
ComplexPythonFunctionCalls: 2149ms 2574ms -16.5%
ConcatStrings: 5129ms 3004ms 70.7%
ConcatUnicode: 3040ms 2602ms 16.8%
CreateInstances: 839ms 2035ms -58.8%
CreateNewInstances: 1121ms 1552ms -27.8%
CreateStringsWithConcat: 2880ms 1113ms 158.8%
CreateUnicodeWithConcat: 809ms 1250ms -35.3%
DictCreation: 2276ms 1052ms 116.3%
DictWithFloatKeys: 2070ms 2956ms -30.0%
DictWithIntegerKeys: 1818ms 851ms 113.8%
DictWithStringKeys: 1990ms 1043ms 90.7%
ForLoops: 562ms 658ms -14.6%
IfThenElse: 291ms 838ms -65.3%
ListSlicing: 3713ms 1493ms 148.7%
NestedForLoops: 640ms 1054ms -39.3%
NormalClassAttribute: 2961ms 1124ms 163.4%
NormalInstanceAttribute: 3710ms 1030ms 260.3%
PythonFunctionCalls: 325ms 1647ms -80.3%
PythonMethodCalls: 3556ms 1866ms 90.6%
Test IPy2.6 CPy2.6.1 Δ
Recursion: 559ms 2214ms -74.8%
SecondImport: 966ms 1248ms -22.6%
SecondPackageImport: 1059ms 1313ms -19.3%
SecondSubmoduleImport: 1496ms 1724ms -13.2%
SimpleComplexArithmetic: 605ms 1324ms -54.3%
SimpleDictManipulation: 2072ms 1094ms 89.4%
SimpleFloatArithmetic: 495ms 1475ms -66.4%
SimpleIntFloatArithmetic: 558ms 760ms -26.6%
SimpleIntegerArithmetic: 542ms 757ms -28.4%
SimpleListManipulation: 1384ms 911ms 51.9%
SimpleLongArithmetic: 1075ms 1197ms -10.2%
SmallLists: 1464ms 1623ms -9.8%
SmallTuples: 871ms 1429ms -39.1%
SpecialClassAttribute: 3210ms 1103ms 190.9%
SpecialInstanceAttribute: 3865ms 1198ms 222.7%
StringMappings: 3055ms 2353ms 29.8%
StringPredicates: 1346ms 1798ms -25.1%
StringSlicing: 1414ms 1522ms -7.1%
TryExcept: 260ms 573ms -54.6%
TryFinally: 949ms 1808ms -47.5%
TryRaiseExcept: 63930ms 1083ms 5805.3%
TupleSlicing: 2090ms 1517ms 37.8%
UnicodeMappings: 2059ms 949ms 117.0%
UnicodePredicates: 1391ms 1297ms 7.2%
UnicodeSlicing: 1399ms 1737ms -19.5%
WithFinally: 652ms 2199ms -70.4%
WithRaiseExcept: 71699ms 1681ms 4164.4%
13
M a r c o P a r e n z a n
Aggiornamento IronPythonal 23 gennaio 2010
• http://ironpython.codeplex.com/• .NET 3.5sp1
– IronPython 2.6• 11 dicembre 2009• http://ironpython.codeplex.com/Release/ProjectReleases.as
px?ReleaseId=12482
• .NET 4.0 Beta 2– IronPython 2.6 CTP for .NET 4.0 Beta 2
• 21 ottobre 2009• http://ironpython.codeplex.com/Release/ProjectReleases.as
px?ReleaseId=28125
14
M a r c o P a r e n z a n
Michael Foordautore di IronPython in Action
• “Why IronPython?”http://ironpython-urls.blogspot.com/2009/12/why-ironpython.html
– No type declarations
– First class and higher order functions
– No need for generics, flexible container types instead
– Protocols and duck-typing instead of compiler enforced interfaces
– First class types and namespaces that can be modified at runtime
– Easy introspection (reflection without the pain)
15
M a r c o P a r e n z a n
No type declarations
• a = 10
• b = "10"
• a+b #fail
• a+int(b) #ok 20
• str(a)+b #ok '1010'
• a = "10" #ok
• a+b #ok '1010'
M a r c o P a r e n z a n
First class and higher order functions
• def Somma(a, b):
• return a+b
• Somma(4,5) # = 9
• s = Somma
• s(4,5) # = 9
M a r c o P a r e n z a n
No need for generics, flexible container types instead
• class BinaryOp:• def __init__(self, a, b):• self.a = a• self.b = b• def Somma(self):• return a+b• ops = []• ops.append(BinaryOp(2,4))• ops.append(BinaryOp(5,5))• ops.append(BinaryOp(8,2))
• for op in ops:• print op.Somma()
M a r c o P a r e n z a n
Protocols and duck-typing instead of compiler enforced interfaces
• class CustomOps:
• def __iter__():
• yield new BinaryOp(3,5)
• yield new BinaryOp(4,3)
• yield new BinaryOp(2,5)
• for op in ops:
• print op.Somma()
M a r c o P a r e n z a n
First class types and namespaces that can be modified at runtime
• ## aggiungere un metodo alla classe• def Differenza(self):• return a-b• BinaryOp.Differenza = Differenza
• ## aggiungere un metodo ad una specifica istanza• import new• def Moltiplica(self):• return a*b• ops[0].Moltiplica = new.instancemethod(Moltiplica, ops[0],
BinaryOp)
M a r c o P a r e n z a n
Easy introspection(reflection without the pain)
• dir(BinaryOp)
• dir(ops[0])
• dir(ops[1])
Beyond .NET
Perché usare IronPython?
M a r c o P a r e n z a n
Bisogna accontentare il cliente
• Scrivere codice dopo il deployment
– On site
– Magari senza aprire Visual Studio
• Modifiche/personalizzazioni continue
• Il deployment è un problema
– Non siamo a “velocità ingegneristiche” (tipicamente lente)
– Rilasci “non controllati”
23
M a r c o P a r e n z a n
Specifiche (1)
• Complessità relativamente bassa – Non si vuole sostituire il C# (Non me ne voglia la community dei
Dynamic Languages)
• Sostituire solo alcuni pezzi– Mansioni accessorie e molto specifiche
• Mancanza di una propria interfaccia grafica– Qui si può disquisire– WPF è scripting
• Una certa linearità– Il flusso di esecuzione viene sempre implementato nel core scritto in
C#
• Quando realmente serve?– Formule, Codice di calcolo, Report (io uso librerie PDF), Import/Export
• Non siamo in condizioni di criticità per le performances
24
Beyond .NET
IronPython come uno scripting Language
M a r c o P a r e n z a n
IronPython DLR
• IronPython 1.0 ha “risolto” l’implementazionedel Python su .NET
• IronPython 2.0 ha “risolto” problematichevalide per “tutti” i Dynamic Languages implementabili
26
Pythonbinder
Rubybinder
COMbinder
JavaScriptbinder
Objectbinder
Dynamic Languages on .NET
Dynamic Language Runtime
Expression Trees Dynamic Dispatch Call Site
IronPython IronRuby C# VB.NET Others…
M a r c o P a r e n z a n
Aggiornamento IronRuby al 23 gennaio 2010
• http://ironruby.codeplex.com/• .NET 3.5sp1
– IronRuby 1.0 RC1 (0.9.3.0)• 20 novembre 2009• http://ironruby.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=35312
– IronPython binaries for ironruby-1.0 RC1 interop (0.9.3.0)• 20 dicembre 2009• http://ironruby.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=35312
#DownloadId=97919
• .NET 4.0 Beta 2– IronRuby CTP for .NET 4.0 Beta 2
• 21 ottobre 2009• http://ironruby.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=35312
#DownloadId=97919
28
M a r c o P a r e n z a n
Aggiornamento DLRal 23 gennaio 2009
• http://dlr.codeplex.com/
• .NET 3.5sp1 e .NET 4.0 Beta 2, solo src
– 22 ottobre 2009
– http://dlr.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=34834
29
M a r c o P a r e n z a n
Hosting IronPython in .NET
• Esempi
– Valutazione di espressioni
– Esecuzione di procedure
– Invocazione di oggetti (dynamic in C# 4.0!)
M a r c o P a r e n z a n
Querying with IronPython
• Interrogare un database tramite IronPython
• EntityFramework può venire in aiuto
• Può essere utile come file batch per fare import/export di dati
M a r c o P a r e n z a n
Reports with IronPython
• Preferisco usare librerie PDF invece di reporting services
• Aggiungere un campo in un report è una cosa comune
• Farlo “on-site” senza aprire Visual Studio è meglio
M a r c o P a r e n z a n
Scripting in WPF
• Personalizzare elementi di una tipica applicazione LOB
• Oltre a personalizzare i report…
• …gestire gli eventi CRUD
M a r c o P a r e n z a n
Domain Specific Languages
• IronPython and DLR come backend per un linguaggio “verticale”, applicativo (appunto un DSL)
M a r c o P a r e n z a n
Conclusioni
• Necessità dello scripting– Risolvere il problema delle personalizzazioni c/o il cliente
• Risolto?– È un gran bel passo avanti– Ma è probabilmente meglio un DSL (con backend il DLR)
• Credenza di fondo– Scelgo di usare ANCHE un altro linguaggio
• “Polyglot programmer”
– Accetto il “compromesso” del “dinamico”
• Attingere ad un parco di implementazioni (tutte open source) eccezionale in maniera nativa (non interop)– Ruby on Rails
37
M a r c o P a r e n z a n
Il team che lavora sul DLR e dintorni
• Jim Hugunin (DLR) – Blog: http://blogs.msdn.com/hugunin/
• Dino Viehland (IronPython) – Blog:
http://blogs.msdn.com/dinoviehland/– Twitter:
http://twitter.com/DinoViehland
• Jimmy Schementi (Silverlight integration)– Blog: http://blog.jimmy.schementi.com/– Twitter: http://twitter.com/jschementi
• John Lam (IronRuby)– Blog: http://www.iunknown.com/– Twitter: http://twitter.com/john_lam/
• Curt Hagenlocher (IronPython)– Blog: http://blogs.msdn.com/curth/
» Dave Fugate (IronPython)
• Blog: http://knowbody.livejournal.com/
• Twitter: http://twitter.com/davefugate
» Harry Pierson (Evangelist)
• Blog: http://www.devhawk.net/
• Twitter: http://twitter.com/DevHawk
» Seo Sanghyeon (IronPython)
• Blog: http://fepy.blogspot.com/
• Twitter: http://twitter.com/sanxiyn
» Jim Deville (IronRuby)
• Blog: http://blog.jredville.com/
• Twitter: http://twitter.com/jredville
» Shri Borde (IronRuby)
• Blog: http://blogs.msdn.com/shrib/
» Tomas Matousek (IronRuby)
• Blog: http://blog.tomasm.net/
38
M a r c o P a r e n z a n
Autori
• Michael Foord
– Libro: http://www.manning.com/foord/
– Blog: http://www.voidspace.org.uk/python/weblog/index.shtml
– Twitter: http://twitter.com/Voidspace
• Ivar Porto Carrero
– Libro: http://www.manning.com/carrero/
– Blog: http://flanders.co.nz/
– Twitter: http://twitter.com/casualjim
39
Grazie
Q & A
40
blog: http://blog.codeisvalue.com/
email: [email protected]
web: http://www.codeisvalue.com/
Skype: marco.parenzan
Messenger [email protected]
Twitter: marco_parenzan