python in the browser: intro to brython
DESCRIPTION
Have you ever wished that you can write Python in the browser? Brython is an experimental Javascript library that enables you to leverage the elegance of Python on the client side. Novice programmers who are familiar with Javascript will learn about Brython, how Brython measures up against Javascript, and why getting client-side Python adopted as a mainstream tool is really difficult.TRANSCRIPT
PythonintheBrowserIntrotoBrython
PyCon2014
SusanTanSoftwareEngineerEmail:[email protected]:@ArcTanSusan
AboutMe
SusanTan,arecentcollegegraduateAlso,anopensourcecontributortoPythonprojects:OpenHatch,Django,IPythonnotebookPreviously,webapplicationengineeratFlixsterwithRottenTomatoesI'maPythondevforhire!I'mlookingforPythonjobsinSanFrancisco.
ThisisatalkaboutaJavascriptlibrary.
QuickLiveDemoofBrython
TableofContents
WhyPythoninthebrowser?ExistingFeaturesinBrythonComparisonofto-dolistappsSimplespeedtestsLimitationsFutureofBrythonandJavascript
Summary:AnevaluationofBrythonfromauserperspective.
Whatthistalkisnotabout
anadpitchdifferentarchitecturalapproachesincreatingpythonimplementationsinthebrowser
WhyPythoninthebrowser?
Forwho?Front-endengineersScientists
Pythonfornumericalcomputinginfront-endalternativeorcomplementtoD3?
Goals:Instantlyinteractivecomputation-heavyUIwidgetsBrowser-onlywebapplicationspoweredbyPython.
WhataresomeexistingPython-to-Javascriptcompilers?
Stand-alonecompilersPythonJSPyjaco
PyjamasPy2JS
In-browserimplementationsSkulptBrython
WhyPythonintheBrowser?
PythonismorefuntowriteandismorereadablethanJavascriptJavascriptstartstogetmessyandunreadableveryquickly
FeaturesofBrythonasource-to-sourcecompiler
Supportforcorepythonmodules,libraries,packagesDOMAPIAvoidproblemsinJavascript
HowtogetstartedwithBrython
1.GettheBrython.jsfile.
2.LoadtheJavascriptlibrarybrython.js:
<scriptsrc="/path/to/brython.js">
3.EmbedPythoncodeinsidehere:
<scripttype="text/python">4.Includethisbodytag:
<bodyonload="brython()">
MinimalSetup
<html><head><scriptsrc="path/to/brython.js"></script></head><bodyonload="brython()"><scripttype="text/python">
"""YourPythonCodeHere."""
</script></body></html>
HowtoaccessDOMelements<divid="UniqueIdHere">SomeTextHere</div>
injquery$("#UniqueIDHere")
inbrythonfrombrowserimportdocdoc["UniqueIDHere"]
or
doc.get(selector="#UniqueIDHere")
Howtoaddandremovecssclasses
injquery$("div").addClass("fooClass")$("div").removeClass("fooClass")
inbrythondiv.classList.remove("fooClass")div.classList.add("anotherclass")
$("#IdHere").append(NewDivElement)
html.LI()<=NewDivElement
HowtocreateDOMelements
inbrython
injquery
<divid="IdHere">SomeTextHere</div>
Tocreateanewdivelementandstoreitinavariable:
Thenappendthenewdivtoanewlycreatedlistelement:
frombrowserimporthtmlNewDivElement=html.DIV(Class="view",Id="uniqueView")
Howtobindeventhandlers
//Bindonclickhandleronbutton?defsayHi():print("hello")
injquery
inbrython
$("#mybutton").bind("click",sayHi)
doc["mybutton"].bind('click',sayHi)
Howtoaccesslocalstorage
injavascript
inbrython
localStorage.setItem("todo_item","Makeacupoftea")
localStorage.getItem("todo_item")
localStorage.removeItem('favoriteflavor')
frombrowser.local_storageimportstorage
storage['foo']='bar'
delstorage['foo']
AccesstoJavascriptlibraries
InBrython,usethejavascriptmodule.Example:howtoaccessjquerylibraryinBrython
fromjavascriptimportJSObjectdefcallback(*args):...
_jQuery=JSObject($("body"))_jQuery.click(callback)
Comparisonofto-dolistapps
LiveDemoTimeAgain
SourceCodeonGitHub:http://bit.ly/1nODxED
Design
Source:http://todomvc.com/
SimpleTimingTestsdefmy_func():a=0N=100,000forxinrange(N):a+=1#IPythonnotebookmagicsyntax%timeit-n1000my_func()#Brythoncodeimporttimet0=time.time()(MyBrythoncodehere)print(time.time()-t0)ResultingAveragesPython27:8msJavascript:5ms,Brython:190ms
AnotherTimingTest
defmy_func2():a=0i=0N=100,000whilei<N:a+=1i+=1
ResultingAveragesPython27:8.57msJavascript:5msBrython:1,000ms
Why?var$next12=getattr(iter(getattr(range,"__call__")(Number(100000))),"__next__")var$no_break12=true;while(true){try{varx=$globals["x"]=$next12();None;}catch($err){if(__BRYTHON__.is_exc($err,[__builtins__.StopIteration])){__BRYTHON__.$pop_exc();break}else{throw($err)}}__BRYTHON__.line_info=[3,"__main__"];None;var$temp=Number(1);None;if($temp.$fast_augm&&a.$fast_augm){a+=$temp;$globals["a"]=a}elseif(!hasattr(a,"__iadd__")){vara=$globals["a"]=getattr(a,"__add__")($temp);None;}else{a=$globals["a"]=getattr(a,"__iadd__")($temp)}}
Ifit'sslow,whyuseit?
Youdon'thavetoTruefull-stackPythonforwebdevelopmentFront-enddata-intensivevisualizations
CorePythonmath,datetime,jsonmodulesaresupported
Limitations
VeryslowNosupportforscientificpythonlibrariesscikit-learn,nltk,scipyarenotsupported.
Nodebuggertoolforpausingcodeduringexecution
Whyisithardtogetanewtoolorlibraryadoptedasmainstream?
Whatproblemdoesitsolve?Isiteasytouseandlearn?Whoelseisusingit?Why?Isitinactivedevelopment?
TheFutureofJavascript?
Javascript6iscomingtoFirefoxAverylargegrowingecosystemasm,dart,typescriptMVCframeworks:Angular,Backbone,Ember,KnockoutAcrowdedmess
Stillbemainstreamforanother5years.
TheFutureofClient-sidePython?
Excitingtimesareahead.
mpld3?PyPy.js?Vispy?IPythonnotebook?
Thanksforlistening!Questions?
SusanTan@ArcTanSusan
ExtraReferenceSlides
HowBrythonmanipulatestheJSnamespaceviaglobalwindow
frombrowserimportwindowwindow.echo=echo
Brython2.0
NamesoffunctionsandclassesdefinedinBrythonarenolongeravailableinJavascriptglobalnamespace.TheonlynamesincludedintheglobalJavascriptnamespaceare__BRYTHON__(usedinternally)andbrython(),thefunctioncalledonpageload.
NewListComprehrensionSyntaxinEcmascript
//Before(byhand)varfoo=(function(){varresult=[];for(varxofy)result.push(x*x);returnresult;})();
//Before(assumingyhasamap()method)varfoo=y.map(function(x){returnx*x});
//Aftervarfoo=[for(xofy)x*x];
NewGeneratorComprehensioninEcmascript
//Beforevarbar=(function*(){for(varxofy)yieldy})();
//Aftervarbar=(for(xofy)y);