Python ve Typing

 

 

@bahattincinic

Bahattin Çiniç

Software Developer @adphorus
http://bahattincinic.com
https://github.com/bahattincinic

Dynamic Typing

text = "Hello Pyistanbul"  # str
text = 1                   # int

# TypeError: cannot concatenate 'str' and 'int' objects
'Bahattin' + 5

Static Typing

int text = 1;

text = "Hello world";  // Compile Error

Java

Duck Typing

class Sparrow:
    def fly(self):
        print("Sparrow flying")

class Airplane:
    def fly(self):
        print("Airplane flying")

class Whale:
    def swim(self):
        print("Whale swimming")

def lift_off(entity):
    entity.fly()

sparrow = Sparrow()
airplane = Airplane()
whale = Whale()

lift_off(sparrow)
# prints `Sparrow flying`
lift_off(airplane)
# prints `Airplane flying`
lift_off(whale)
# Throws the error `'Whale' object has
# no attribute 'fly'`

Eğer ördek gibi yürüyorsa ve ördek gibi konuşuyorsa, o vakit ona ördek muamelesi yapabiliriz. yani bir object aradığımız method'ları sağlıyorsa onun class'ının ne olduğu önemli değildir.

Strong Typing

/* Python code */ 
>>> foo = "x" 
>>> foo = foo + 2 
Traceback (most recent call last): 
  File "<pyshell#3>", line 1, in ? 
    foo = foo + 2 
TypeError: cannot concatenate 'str' and 'int' objects 

bir programlama dilinde değişkenlerin değerlerinin türlerine uyumlu olup olmadığının kontrol edilme özelliğidir.en güzel örneklerinden biri javadır.

Weak Typing

/* PHP code */ 
<?php 
$foo = "x"; 
$foo = $foo + 2; // not an error 
echo $foo; 
?>

Strong typed dillerin aksine, weak typed diller, değişkenlerin tipleri olmadığı anlamına gelmediği belirtilmelidir; bu, değişkenlerin belirli bir veri türüne "bağlı" olmadığı anlamına gelir. PHP ve C, weak typed dillere örnektir.

Neden Static Typing ?

  • Olası hataların development ortamında yakalanması.
  • Type seni kod yazarken yönlendirir.
  • Refactor edebilmesi daha kolay
  • Otomatik dökümantasyon oluşturabilmek.
  • Compiler optimizasyonu için kolaylık.
  • IDE lere kolaylık.
  • Unit testini yazmak çok daha kolay.

Static Typing Dezavantajları?

  • Çok Katı
  • Prototip çıkarmak daha çok vakit alabilir.
  • Daha az ayrıntı.
  • Kullanımı daha zor.
  • Programlama deneyimi gerektiriyor.
  • Deployment daha zor.

Covariance, Contravariance, Bivariance, and Invariance

Invariance

  • Invariance supertypes kabul etmiyor.
  • Invariance subtypes kabul etmiyor.

Covariance

  • Covariance supertypes kabul etmiyor.
  • Covariance subtypes kabul ediyor.

Contravariance

  • Contravariance supertypes kabul ediyor.
  • Contravariance subtypes kabul etmiyor.

Bivariance

  • Bivariance supertypes kabul ediyor.
  • Bivariance subtypes kabul ediyor.

http://bit.ly/2yV2hDn

Daha Fazla Bilgi icin

PEP Proposals

Semantic model:
    PEP 483 — The Theory of Type Hints
Type annotation syntax:
    PEP 484 — Type Hints

Syntax for Variable Annotations:
    PEP 526
Checking & reporting tool:
    MyPy

Mypy

Mypp Python icin bir static type checker. Official olarak Python tarafından geliştiriliyor. Mypy bir static type analyzer ve aynı zamanda bir lint uygulaması.

 

İlk versiyonunu  Jukka Lehtosalo geliştirdi.

 

http://github.com/python/mypy

Mypy Kullanımı

$ pip install mypy
$ mypy *.py


$ mypy hello.py

Kullanım

Kurulum

Python 2 Compatible ?

http://mypy.readthedocs.io/en/latest/python2.html

$ mypy --py2 program.py

Example (Hello World)

# example.py

def message(name: str) -> str:
    return 'Hello, {}'.format(name)


print(message(1))


"""
mypy example.py
example.py:5: error: Argument 1 to "greeting" has
incompatible type "int"; expected "str"
"""

Type Comments

from typing import List

nums = []   # type: List[int]

nums.append('Hello')

print(nums)
$ mypy a.py
a.py:5: error: Argument 1 to "append" of "list" has incompatible
type "str"; expected "int"

PEP 526 — Variable and Attribute Annotations

from typing import List

nums: List[int] = []

x: str = 'Hello'

nums.append(1)
nums.append('Tr')

print(x)
$ mypy d.py
d.py:6: error: Argument 1 to "append" of "list" has incompatible
type "str"; expected "int"

Type Aliases

from typing import List
Vector = List[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])

NewType

from typing import NewType

UserId = NewType('UserId', int)

def get_user_name(user_id: UserId) -> str:
    return 'Hello'


get_user_name(UserId(42351))

Callable

from typing import Callable


def f(num1: int, my_float: float) -> float:
    return num1 + my_float


x = f # type: Callable[[int, float], float]

Generics

from typing import Sequence, TypeVar

T = TypeVar('T')      # Declare type variable

def first(l: Sequence[T]) -> T:   # Generic function
    return l[0]
Sequence Types: str, unicode, list, tuple..

Any

from typing import Any

a = None    # type: Any
a = []      # OK
a = 2       # OK

s = ''      # type: str
s = a       # OK

def foo(item: Any) -> int:
    # Typechecks; 'item' could be any type,
    # and that type might have a 'bar' method
    item.bar()

Çok Daha Fazlası

  • typing.Iterable
  • typing.Iterator
  • typing.Hashable
  • typing.Sequence
  • typing.List
  • typing.Set
  • typing.FrozenSet
  • typing.Awaitable
  • typing.Coroutine
  • typing.Dict
  • typing.Counter
  • typing.Optional
  • typing.Union

...

Çok Daha Fazlası

  • typing.Iterable
  • typing.Iterator
  • typing.Hashable
  • typing.Sequence
  • typing.List
  • typing.Set
  • typing.FrozenSet
  • typing.Awaitable
  • typing.Coroutine
  • typing.Dict
  • typing.Counter
  • typing.Optional
  • typing.Union

...

Sorular ?

Teşekkürler

Made with Slides.com