Go for Python Programmers by Shahriar Tajbakhsh at EuroPython 2016 - - PowerPoint PPT Presentation

go for python programmers
SMART_READER_LITE
LIVE PREVIEW

Go for Python Programmers by Shahriar Tajbakhsh at EuroPython 2016 - - PowerPoint PPT Presentation

Go for Python Programmers by Shahriar Tajbakhsh at EuroPython 2016 Shahriar Tajbakhsh Software Engineer @ Osper github.com/s16h twitter.com/STajbakhsh shahriar.svbtle.com Opposite of P.S. As I prepared this talk, I realised that it was


slide-1
SLIDE 1

Go for Python Programmers

by Shahriar Tajbakhsh at EuroPython 2016

slide-2
SLIDE 2

Shahriar Tajbakhsh

Software Engineer @ Osper github.com/s16h twitter.com/STajbakhsh shahriar.svbtle.com

slide-3
SLIDE 3

Opposite of P.S.

As I prepared this talk, I realised that it was probably a bad idea…

slide-4
SLIDE 4

Why is this talk a bad idea?

It kind of implies writing/using Go as you would write Python; which is bad because it leads to un-idiomatic Go code.

slide-5
SLIDE 5

Is it really that bad?

I’m fairly sure it is.

slide-6
SLIDE 6

Anyhow…

slide-7
SLIDE 7

Talk Structure

  • 1. Quick overview of history.
  • 2. Comparison of general syntax and semantics.
  • 3. Ecosystem and tools of Go and Python.
slide-8
SLIDE 8

History

slide-9
SLIDE 9

First appeared in 2009.

Influenced by ALGOL 60, Pascal, C, CSP, Modula-2, Squeak, Oberon-2, Alef…

First appeared in 1991.

Influenced by ABC, ALGOL 68, C, C++, Dylan, Haskell, Icon, Java, Lisp, Modula-3, Perl…

slide-10
SLIDE 10

Syntax and Semantics

slide-11
SLIDE 11

def main(): text = 'Hello, world!' print(text) if __name__ == '__main__': main() package main import "fmt" func main() { text := "Hello, world!" fmt.Println(text) }

slide-12
SLIDE 12

Package

Every .go file has to have a package declaration.

package main import "fmt" func main() { text := "Hello, world!" fmt.Println(text) }

slide-13
SLIDE 13

Package

All .go files in the same directory must have the same package name.

package main import "fmt" func main() { text := "Hello, world!" fmt.Println(text) }

slide-14
SLIDE 14

Import

Usage is very similar to Python.

package main import "fmt" func main() { text := "Hello, world!" fmt.Println(text) }

slide-15
SLIDE 15

Import

Each package to be imported is listed on a separate line, inside quotation marks.

package main import "fmt" func main() { text := "Hello, world!" fmt.Println(text) }

slide-16
SLIDE 16

Functions

😭

We’ll talk about them later.

package main import "fmt" func main() { text := "Hello, world!" fmt.Println(text) }

slide-17
SLIDE 17

Variable Deceleration

package main import "fmt" func main() { text := "Hello, world!" fmt.Println(text) }

text is a of type string. That’s inferred by the compiler, in this case.

slide-18
SLIDE 18

Types

Not quite categorised in the same way as Go. Go-style interfaces don’t really exist Python. Four categories: basic, aggregate, reference and interface

slide-19
SLIDE 19

Basic Data Types

int, int8, int16, int32, int64 long uint, uint8, uint16, uint32, uint64 long float, float32, float64 float complex64, complex128 complex bool bool string str

slide-20
SLIDE 20

Aggregate Types

array array struct ~class (maybe more of a namedtuple)

slide-21
SLIDE 21

Reference Types

slices list maps dict channels

🤕

slide-22
SLIDE 22

Interface Types

Used to express generalisation or abstractions about the behaviour of other types. We’ll talk a bit more about them later.

slide-23
SLIDE 23

Deceleration and Usage

var text string text = "Some string!" var count uint = 2 pi := 3.14

Storage location, with specific type and an associated name.

slide-24
SLIDE 24

Zero Values

var text string text = "Some string!" var count uint = 2 pi := 3.14

text is "" at this point. Variables declared without an explicit initial value are given their zero value.

slide-25
SLIDE 25

Fun with Zero Values

counts := make(map[string]int) input := bufio.NewScanner(os.stdin) for input.Scan() { counts[input.Text()]++ }

We would use Counter but Go’s zero value results in behaviour that we would get with

defaultdict.

slide-26
SLIDE 26

Functions

func name(parameter-list) (result-list) { body } def name(*args, **kwargs): body

slide-27
SLIDE 27

Functions

func Adder(a int, b int) int { return a + b }

Example of a useless function.

slide-28
SLIDE 28

Functions

func Adder(a int, b int) (c int) { c = a + b return c }

You can also have named results.

slide-29
SLIDE 29

Functions

func Adder(a int, b int) (c int) { c = a + b return a + b }

Type of a function is called its signature. It is defined by sequence of parameter types and sequence of result types.

slide-30
SLIDE 30

Functions

Like in Python, functions in Go are first-class

  • values. They can be passed around.

They’re zero value is nil.

slide-31
SLIDE 31

Functions

func Size() (int, int) { return 1, 2 } width, height := Size()

Just like Python, functions can return more than one result. These functions return a tuple of values.

slide-32
SLIDE 32

Errors and Error Handling

try: something... except: handle… else: success... finally: whatever... result, err = Foo() if err != nil { // It's all good } else { // An error occurred. }

slide-33
SLIDE 33

Errors and Error Handling

func main() { f := createFile("/tmp/foo.txt") defer closeFile(f) . . . }

Defer is used to ensure that a function call is performed later in a program’s execution, usually for purposes of cleanup.

slide-34
SLIDE 34

Errors and Error Handling

But sometimes, there are genuinely exceptional

  • circumstances. For example, when running out
  • f memory or out-of-bounds array access.
slide-35
SLIDE 35

Errors and Error Handling

In these exceptional cases, Go panics.

slide-36
SLIDE 36

Errors and Error Handling

When Go panics:

  • 1. Normal execution stops.
  • 2. All deferred function (in that goroutine) calls are

executed.

  • 3. Program crashes with a log message.
slide-37
SLIDE 37

Errors and Error Handling

Although giving up is usually the right response to a panic, it might sometimes make sense to try and recover from it; at least for clean-up.

slide-38
SLIDE 38

Errors and Error Handling

func Parse(input string) (s *Syntax, err error) { defer func() { if p := recover(); p != nil { err = fmt.Errorf("internal error: %v", p) } }() // ... parser... }

slide-39
SLIDE 39

What about OOP?

As we know, Python is object oriented. It has all the fancy stuff: classes, inheritance etc. Go can also be considered object oriented but not in the same way as Python.

slide-40
SLIDE 40

OOP in Go

Go says an object is simply a value or variable that has methods, and a method is a function associated with a particular type.

slide-41
SLIDE 41

OOP in Go

There is no support for inheritance in Go.

Composition it is.

slide-42
SLIDE 42

OOP

class Point: def __init__(self, x, y): self.x = x self.y = y type Point struct { X float64 Y float64 }

slide-43
SLIDE 43

OOP

class Point: def __init__(self, x, y): self.x = x self.y = y def distance(self, other): return math.sqrt( (other.x - self.x) ** 2 + (other.y - self.y) ** 2 ) type Point struct { X float64 Y float64 } func (p Point) Distance(q Point) float64 { return math.Hypot(q.X-p.X, q.Y-p.Y) }

slide-44
SLIDE 44

OOP

As mentioned, Go doesn’t have inheritance. But it composes types by struct embedding. Composes what by what whatting!?

slide-45
SLIDE 45

Struct Embedding

type Point struct { X float64 Y float64 } type NamedPoint struct { Point Name string }

slide-46
SLIDE 46

Struct Embedding

point := Point{1, 2} namedPoint := NamedPoint(point, "Osper") fmt.Println(namedPoint.X) // 1.0 fmt.Println(namedPoint.Distance(point)) // 0.0 fmt.Println(namedPoint.Name) // Osper

slide-47
SLIDE 47

Anything else OOP-esque?

🤕

slide-48
SLIDE 48

Anything else OOP-esque?

I mentioned Go interfaces earlier. Conceptually, they are in fact very similar to duck-typing in Python.

slide-49
SLIDE 49

Interfaces

A type satisfies an interface if it posses all the methods the interface requires.

slide-50
SLIDE 50

Interfaces

type Writer interface { Write(p []byte) (n int, err error) } type Reader interface { Read(p []byte) (n int, err error) } type ReadWriter interface { Reader Writer }

slide-51
SLIDE 51

Concurrency

Go’s support for concurrency is considered one

  • f its strengths.

In Python…LOL (I joke!)

slide-52
SLIDE 52

Concurrency

  • 1. goroutines

(Communicating Sequential Processes)

  • 2. Traditional shared

memory.

threading (ROFL), multiprocessing, asyncio…

slide-53
SLIDE 53

Goroutines

Light-weight threads managed by the go runtime. To start a new goroutine, just prepend go to a function call.

slide-54
SLIDE 54

Goroutines

Light-weight threads managed by the go runtime. To start a new goroutine, just prepend go to a function call.

slide-55
SLIDE 55

Goroutines

package main import ( "fmt" "time" ) func WasteTime(delay time.Duration) { time.Sleep(delay) fmt.Println("Time wasted!") } func main() { go WasteTime(2000 * time.Millisecond) fmt.Println("End of main()") time.Sleep(4000 * time.Millisecond) }

slide-56
SLIDE 56

Channels

Channels are a typed “buffer” through which you can send and receive values between goroutines.

slide-57
SLIDE 57

Channels

package main import "fmt" func main() { // create new channel of type int ch := make(chan int) // start new anonymous goroutine go func() { // send 42 to channel ch <- 42 }() // read from channel fmt.Println(<-ch) }

slide-58
SLIDE 58

Ecosystem and Tools

slide-59
SLIDE 59

Testing

$ go test … unittest is pretty good. py.test is sweet. Lots of really good and mature tools.

slide-60
SLIDE 60

Testing

$ go test …

By convention, files whose name ends in _test.go are test files.

slide-61
SLIDE 61

Code Formatting

$ go fmt source.go PEP 8 Use tools such as flake8

slide-62
SLIDE 62

Package Management

$ go get package

Will fetch a remote packages, compile it and install it.

Quite a few different tools

  • ne can use (e.g. pip).

Some think it’s a mess.

slide-63
SLIDE 63

Package Management

$GOPATH environment variable used to specify the location of your workspace. virtualenv is widely used for managing per- project dependencies.

slide-64
SLIDE 64

Documentation Generation

$ go doc …

Godoc extracts and generates documentation for Go programs.

Different tools for automatic and manual doc generation (e.g. Sphinx, autodoc, PyDoc etc.).

slide-65
SLIDE 65

Conclusion

😂

slide-66
SLIDE 66

Shahriar Tajbakhsh

Software Engineer @ Osper github.com/s16h twitter.com/STajbakhsh shahriar.svbtle.com

That’s all, Thanks!

slide-67
SLIDE 67

Q&PA

Questions and Possible Answers