SlideShare une entreprise Scribd logo
1  sur  50
Télécharger pour lire hors ligne
 




Utan stödhjul och 
   motorsåg
Vad är Python?




● Ett dynamiskt typat språk
● Designat för enkelhet och tydlighet
It is the only language co-designed for the
  most advanced and the complete novice.

             [David Goodger]
Plattformar



● Python = CPython
● Jython (JVM)

● IronPython (.NET, Mono)

● PyPy (Python in Python)
Användningsområden

admin, byggen och driftsättning

webbapps, webbtjänster/+klienter

verktygsklister & GUIn (vanligt på linux)

dataskyffling/-konvertering/-analys
Scripta verktyg


Grafik (Gimp, Inkscape, Blender, ...), 
LibreOffice, ...

Spel (Battlefield 2+, Civ IV, EVE-Online, ...)

DVCS: Mercurial, Bazaar...
Användare
.. Sun, Microsoft, Canonical, O'Reilly, Lucasfilm, 
Nasa, Sourceforge, ...
Årets språk enligt Tiobe


      Bästa tillväxten

           2007
           2010
Moget


Utveckling & drift: doctest, nosetests, distribute,
pip, virtualenv, ...

Paket för allt: data, sysadmin, webb, grafik,
matematik, parallellism...
Design
Vad är viktigt?



Läsbarhet!

Namngivning!
Programming The 
Way Guido Indented It
def to_roman(num):

    assert num > 0 and num < 4000

    result = []

    for d, r in NUMERALS:

        while num >= d:
            result.append(r)
            num -= d

    return ''.join(result)
"In soviet russia, braces scope you"


from __future__ import braces


...
SyntaxError: not a chance
Effektivt


tokens = ['a', 'b', 'c', 'B', 'dd', 'C', 'DD']

similar = {}

for token in tokens:
    key = token.lower()
    similar.setdefault(key, []).append(token)
Lättanvänt


for key, tokens in similar.items():

    if len(tokens) > 1:
        print("Similar (like %s):" % key)

        for token in tokens:
            print(token)
Generella behållare



● list() == []
● dict() == {}

● tuple() == ()

● set()
Python är interaktivt



$ python
Python 2.7.1 [...]
Type "help", "copyright", "credits" or "license" for
more information.
>>>
>>>   def add(a, b=1):
...       return a + b
...
>>>   add(1)
2
>>>   add(1, 2)
3
>>>   add(2, b=3)
5
>>>   add(b=3, a=2)
5
Mekanik
"""
Usage:

      >>> usr = Path('/usr')
      >>> bin = usr.segment('local').segment('bin')
      >>> str(bin)
      '/usr/local/bin'
"""

class Path:
    def __init__(self, base):
        self.base = base

      def segment(self, name):
          return Path(self.base + '/' + name)

      def __str__(self):
          return self.base
__protokoll__




Betyder används under ytan
Tydliga sammanhang



Börjar bukta när en dålig idé växer

●   state är explicit (self)
"""
Usage:

      >>> usr = Path('/usr')
      >>> bin = usr.segment('local').segment('bin')
      >>> str(bin)
      '/usr/local/bin'
"""

class Path(str):
    def segment(self, name):
        return Path(self + '/' + name)
Allt är objekt



● primitiver
● collections

● funktioner, klasser

● moduler, paket
Ingen motorsåg..
"""Usage:
                      Closures
      >>> mkpasswd = salter("@secret#salt")
      >>> mkpasswd("qwerty")
      '4ef6056fb6f424f2e848705fd5e40602'
"""

from hashlib import md5

def salter(salt):

      def salted_encrypt(value):
          return md5(salt + value).hexdigest()

      return salted_encrypt


 
Funktionell @dekoration


from django.views.decorators.cache import cache_page

@cache_page(15 * 60)
def slashdot_index(request):
    result = resource_intensive_operation(request)
    return view_for(result)
Reduce boilerplate..


try:
    f = open('file1.txt')
    for line in f:
        print(line)

finally:
    f.close()
.. with contexts



with open('file1.txt') as f:

    for line in f:
        print(line)
Generators


def public_files(dirname):
    for fname in os.listdir(dirname):
        if not fname.startswith('.'):
            yield fname

for fname in public_files('.'):
    open(fname)
Projicera data
Maskinellt procedurell


publicfiles = []

for fname in os.listdir('.'):

    if not fname.startswith('.'):
        publicfiles.append(open(fname))
Tillståndslös spaghetti



publicfiles = map(lambda fname: open(fname),
                  filter(lambda fname:
                            not fname.startswith('.'),
                         os.listdir('.')))
List comprehensions



publicfiles = [open(fname)
               for fname in os.listdir('.')
               if not fname.startswith('.')]
Generator comprehensions



publicfiles = (open(fname)
               for fname in os.listdir('.')
               if not fname.startswith('.'))
process(open(fname) for fname in os.listdir('.')
        if not fname.startswith('.'))
Myter
"My way or the highway"
Sanningar
There should be one — and 
preferably only one — obvious 
         way to do it.
Although that way may not be 
 obvious at first unless you're 
            Dutch.
Python is humanism
Python ger dig




● Enkel men kraftfull kod
● Fokus på lösningen
Tack!
Image Tributes (CC)
Python, Google, YouTube, Spotify logos & Amazon Python Day Poster photo courtesy of 
respective organization.

Night train

"And so thy path shall be a track of light"

"Documents Reveal Django Pony, Caught In Tail Of Lies." / _why

"inch by inch"

"Wasserglas"

"I am Jack, hear me lumber!"

"Bend me, Shape me, any way you want me."

Contenu connexe

Tendances

Fertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureFertile Ground: The Roots of Clojure
Fertile Ground: The Roots of Clojure
Mike Fogus
 
Happy Go Programming Part 1
Happy Go Programming Part 1Happy Go Programming Part 1
Happy Go Programming Part 1
Lin Yo-An
 

Tendances (20)

Frege is a Haskell for the JVM
Frege is a Haskell for the JVMFrege is a Haskell for the JVM
Frege is a Haskell for the JVM
 
Descobrindo a linguagem Perl
Descobrindo a linguagem PerlDescobrindo a linguagem Perl
Descobrindo a linguagem Perl
 
Chrome拡張開発者のためのFirefox拡張開発
Chrome拡張開発者のためのFirefox拡張開発Chrome拡張開発者のためのFirefox拡張開発
Chrome拡張開発者のためのFirefox拡張開発
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
NUMOSS 4th Week - Commandline Tutorial
NUMOSS 4th Week - Commandline TutorialNUMOSS 4th Week - Commandline Tutorial
NUMOSS 4th Week - Commandline Tutorial
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기
 
(Fun clojure)
(Fun clojure)(Fun clojure)
(Fun clojure)
 
Communities - Perl edition (RioJS)
Communities - Perl edition (RioJS)Communities - Perl edition (RioJS)
Communities - Perl edition (RioJS)
 
Alta performance com Python
Alta performance com PythonAlta performance com Python
Alta performance com Python
 
Python basic
Python basic Python basic
Python basic
 
PubNative Tracker
PubNative TrackerPubNative Tracker
PubNative Tracker
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Introduction of ES2015
Introduction of ES2015Introduction of ES2015
Introduction of ES2015
 
D-Talk: What's awesome about Ruby 2.x and Rails 4
D-Talk: What's awesome about Ruby 2.x and Rails 4D-Talk: What's awesome about Ruby 2.x and Rails 4
D-Talk: What's awesome about Ruby 2.x and Rails 4
 
Introduction to jRuby
Introduction to jRubyIntroduction to jRuby
Introduction to jRuby
 
Fertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureFertile Ground: The Roots of Clojure
Fertile Ground: The Roots of Clojure
 
Intro
IntroIntro
Intro
 
Lập trình Python cơ bản
Lập trình Python cơ bảnLập trình Python cơ bản
Lập trình Python cơ bản
 
Happy Go Programming Part 1
Happy Go Programming Part 1Happy Go Programming Part 1
Happy Go Programming Part 1
 

Similaire à Python utan-stodhjul-motorsag

Python-GTK
Python-GTKPython-GTK
Python-GTK
Yuren Ju
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
ConFoo
 

Similaire à Python utan-stodhjul-motorsag (20)

Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Intro
IntroIntro
Intro
 
C# to python
C# to pythonC# to python
C# to python
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
 
Python-GTK
Python-GTKPython-GTK
Python-GTK
 
PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...
PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...
PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Python basic
Python basicPython basic
Python basic
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010
 
Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a Pythonist
 
Ansible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife OrchestrationAnsible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife Orchestration
 
Golang
GolangGolang
Golang
 
Music as data
Music as dataMusic as data
Music as data
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
 

Plus de niklal (6)

Something Specific and Simple
Something Specific and SimpleSomething Specific and Simple
Something Specific and Simple
 
Länkad Data
Länkad DataLänkad Data
Länkad Data
 
(first '(Clojure.))
(first '(Clojure.))(first '(Clojure.))
(first '(Clojure.))
 
Webbens Arkitektur
Webbens ArkitekturWebbens Arkitektur
Webbens Arkitektur
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 
Groovy Fly Through
Groovy Fly ThroughGroovy Fly Through
Groovy Fly Through
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

Python utan-stodhjul-motorsag