python in the browser: intro to brython

33
Python in the Browser Intro to Brython PyCon 2014 Susan Tan Software Engineer Email: [email protected] Twitter: @ArcTanSusan

Upload: susan-tan

Post on 25-Dec-2014

432 views

Category:

Engineering


5 download

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

Page 1: Python In The Browser: Intro to Brython

PythonintheBrowserIntrotoBrython

PyCon2014

SusanTanSoftwareEngineerEmail:[email protected]:@ArcTanSusan

Page 2: Python In The Browser: Intro to Brython

AboutMe

SusanTan,arecentcollegegraduateAlso,anopensourcecontributortoPythonprojects:OpenHatch,Django,IPythonnotebookPreviously,webapplicationengineeratFlixsterwithRottenTomatoesI'maPythondevforhire!I'mlookingforPythonjobsinSanFrancisco.

Page 3: Python In The Browser: Intro to Brython

ThisisatalkaboutaJavascriptlibrary.

Page 4: Python In The Browser: Intro to Brython

QuickLiveDemoofBrython

Page 5: Python In The Browser: Intro to Brython

TableofContents

WhyPythoninthebrowser?ExistingFeaturesinBrythonComparisonofto-dolistappsSimplespeedtestsLimitationsFutureofBrythonandJavascript

Summary:AnevaluationofBrythonfromauserperspective.

Page 6: Python In The Browser: Intro to Brython

Whatthistalkisnotabout

anadpitchdifferentarchitecturalapproachesincreatingpythonimplementationsinthebrowser

Page 7: Python In The Browser: Intro to Brython

WhyPythoninthebrowser?

Forwho?Front-endengineersScientists

Pythonfornumericalcomputinginfront-endalternativeorcomplementtoD3?

Goals:Instantlyinteractivecomputation-heavyUIwidgetsBrowser-onlywebapplicationspoweredbyPython.

Page 8: Python In The Browser: Intro to Brython

WhataresomeexistingPython-to-Javascriptcompilers?

Stand-alonecompilersPythonJSPyjaco

PyjamasPy2JS

In-browserimplementationsSkulptBrython

Page 9: Python In The Browser: Intro to Brython

WhyPythonintheBrowser?

PythonismorefuntowriteandismorereadablethanJavascriptJavascriptstartstogetmessyandunreadableveryquickly

Page 10: Python In The Browser: Intro to Brython

FeaturesofBrythonasource-to-sourcecompiler

Supportforcorepythonmodules,libraries,packagesDOMAPIAvoidproblemsinJavascript

Page 11: Python In The Browser: Intro to Brython

HowtogetstartedwithBrython

1.GettheBrython.jsfile.

2.LoadtheJavascriptlibrarybrython.js:

<scriptsrc="/path/to/brython.js">

3.EmbedPythoncodeinsidehere:

<scripttype="text/python">4.Includethisbodytag:

<bodyonload="brython()">

Page 12: Python In The Browser: Intro to Brython

MinimalSetup

<html><head><scriptsrc="path/to/brython.js"></script></head><bodyonload="brython()"><scripttype="text/python">

"""YourPythonCodeHere."""

</script></body></html>

Page 13: Python In The Browser: Intro to Brython

HowtoaccessDOMelements<divid="UniqueIdHere">SomeTextHere</div>

injquery$("#UniqueIDHere")

inbrythonfrombrowserimportdocdoc["UniqueIDHere"]

or

doc.get(selector="#UniqueIDHere")

Page 14: Python In The Browser: Intro to Brython

Howtoaddandremovecssclasses

injquery$("div").addClass("fooClass")$("div").removeClass("fooClass")

inbrythondiv.classList.remove("fooClass")div.classList.add("anotherclass")

Page 15: Python In The Browser: Intro to Brython

$("#IdHere").append(NewDivElement)

html.LI()<=NewDivElement

HowtocreateDOMelements

inbrython

injquery

<divid="IdHere">SomeTextHere</div>

Tocreateanewdivelementandstoreitinavariable:

Thenappendthenewdivtoanewlycreatedlistelement:

frombrowserimporthtmlNewDivElement=html.DIV(Class="view",Id="uniqueView")

Page 16: Python In The Browser: Intro to Brython

Howtobindeventhandlers

//Bindonclickhandleronbutton?defsayHi():print("hello")

injquery

inbrython

$("#mybutton").bind("click",sayHi)

doc["mybutton"].bind('click',sayHi)

Page 17: Python In The Browser: Intro to Brython

Howtoaccesslocalstorage

injavascript

inbrython

localStorage.setItem("todo_item","Makeacupoftea")

localStorage.getItem("todo_item")

localStorage.removeItem('favoriteflavor')

frombrowser.local_storageimportstorage

storage['foo']='bar'

delstorage['foo']

Page 18: Python In The Browser: Intro to Brython

AccesstoJavascriptlibraries

InBrython,usethejavascriptmodule.Example:howtoaccessjquerylibraryinBrython

fromjavascriptimportJSObjectdefcallback(*args):...

_jQuery=JSObject($("body"))_jQuery.click(callback)

Page 19: Python In The Browser: Intro to Brython

Comparisonofto-dolistapps

LiveDemoTimeAgain

SourceCodeonGitHub:http://bit.ly/1nODxED

Design

Source:http://todomvc.com/

Page 20: Python In The Browser: Intro to Brython

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

Page 21: Python In The Browser: Intro to Brython

AnotherTimingTest

defmy_func2():a=0i=0N=100,000whilei<N:a+=1i+=1

ResultingAveragesPython27:8.57msJavascript:5msBrython:1,000ms

Page 22: Python In The Browser: Intro to Brython

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)}}

Page 23: Python In The Browser: Intro to Brython

Ifit'sslow,whyuseit?

Youdon'thavetoTruefull-stackPythonforwebdevelopmentFront-enddata-intensivevisualizations

CorePythonmath,datetime,jsonmodulesaresupported

Page 24: Python In The Browser: Intro to Brython

Limitations

VeryslowNosupportforscientificpythonlibrariesscikit-learn,nltk,scipyarenotsupported.

Nodebuggertoolforpausingcodeduringexecution

Page 25: Python In The Browser: Intro to Brython

Whyisithardtogetanewtoolorlibraryadoptedasmainstream?

Whatproblemdoesitsolve?Isiteasytouseandlearn?Whoelseisusingit?Why?Isitinactivedevelopment?

Page 26: Python In The Browser: Intro to Brython

TheFutureofJavascript?

Javascript6iscomingtoFirefoxAverylargegrowingecosystemasm,dart,typescriptMVCframeworks:Angular,Backbone,Ember,KnockoutAcrowdedmess

Stillbemainstreamforanother5years.

Page 27: Python In The Browser: Intro to Brython

TheFutureofClient-sidePython?

Excitingtimesareahead.

mpld3?PyPy.js?Vispy?IPythonnotebook?

Page 28: Python In The Browser: Intro to Brython

Thanksforlistening!Questions?

SusanTan@ArcTanSusan

Page 29: Python In The Browser: Intro to Brython

ExtraReferenceSlides

Page 30: Python In The Browser: Intro to Brython

HowBrythonmanipulatestheJSnamespaceviaglobalwindow

frombrowserimportwindowwindow.echo=echo

Page 31: Python In The Browser: Intro to Brython

Brython2.0

NamesoffunctionsandclassesdefinedinBrythonarenolongeravailableinJavascriptglobalnamespace.TheonlynamesincludedintheglobalJavascriptnamespaceare__BRYTHON__(usedinternally)andbrython(),thefunctioncalledonpageload.

Page 32: Python In The Browser: Intro to Brython

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];

Page 33: Python In The Browser: Intro to Brython

NewGeneratorComprehensioninEcmascript

//Beforevarbar=(function*(){for(varxofy)yieldy})();

//Aftervarbar=(for(xofy)y);