https://xkcd.com/353/
A C# Dev’s Guide to Python
Presented by:
Sarah Dutkiewicz
Microsoft MVP, Visual Studio and
Development Technologies
Microsoft Developers HK
13 June, 2018
About the Presenter
• 9 time Microsoft Most Valuable
Professional – 2 years in Visual C#, 7 years
in Visual Studio and Development Tools
• Bachelor of Science in Computer Science &
Engineering Technology
• Published author of a PowerShell book
• Live coding stream guest on Fritz and
Friends and DevChatter
• Why Hong Kong? #ancestraltrip!
The Python Community
Python’s community is vast;
diverse & aims to grow;
Python is Open.
https://www.python.org/community/
Diversity in Python
The Python Software Foundation and the global Python
community welcome and encourage participation by
everyone. Our community is based on mutual respect,
tolerance, and encouragement, and we are working to help
each other live up to these principles. We want our
community to be more diverse: whoever you are, and
whatever your background, we welcome you.
https://www.python.org/community/diversity/
The Zen of Python,
by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
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.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
https://www.python.org/dev/peps/pep-0020
Areas Using Python
• Analysis
• Computation
• Math
• Science
• Statistics
• Engineering
• Deep Learning
• Artificial Intelligence
• Machine Learning
• Data Science
Weakness of Python
• The Great Python Schism
• Hard version split between 2.x and 3.x
• Some people are stuck on 2.x due to dependencies following the 2.x line
• Greatly opinionated
There should be one-- and preferably only one --obvious way to do it.
Why Python 3?
• Python 2 struggles with text and binary data
• ‘abcd’ is both a string consisting of letters (textual) and a string consisting of
bytes (binary)
• Goes against the “preferably one way” part of the Zen of Python
• Doesn’t do well with Unicode
• Python was out before Unicode was a standard
• Not all projects in Python 2 support Unicode equally
• Python 3
• unicode/str/bytes types
• Backwards-incompatible – but very much necessary, as Python is a language
of the world
Python Enhancement Proposals (PEPs)
• https://www.python.org/dev/peps/
• Purpose and Guidelines for PEPs
• Guidelines for Language Evolution
• Deprecation of Standard Modules
• Bug Fixes
• Style Guides
• Docstring Conventions
• API for crypto
• API for Python database
• Python release schedules
• … and more!
Other Terms…
• Benevolent Dictator for Life (BDFL) – Guido van
Rossum, father of Python
• Pythonista – Python developer
• Pythonic – code follows common guidelines, written
in idiomatic Python
• Pythoneer – pioneers of Python, leaders who create
change
• A Pythoneer can be a Pythonista, but not all
Pythonistas are Pythoneers.
Some Tools to Know
• Visual Studio with Python Tools
• Visual Studio Code
• Azure Notebooks
• Repl.it
• Jupyter Notebooks
• PyCharm
Package Management
• Think NuGet only for Python
• Pip (Pip Installs Packages)
• Python’s official package manager
• Virtualenv
• Install pip packages in an isolated manner
• Conda – conda.io
• Not Python-specific – a cross-platform option similar
to apt and yum
• Part of Miniconda
• Just conda and its dependencies
• Also part of Anaconda
• Conda, its dependencies, and many packages helpful in
data science applications
• More than one? Isn’t this anti-Zen? Yes,
but…
http://jakevdp.github.io/blog/2016/08/25/co
nda-myths-and-misconceptions/
Presentation Breakdown
• Simple Python demos in a Jupyter Notebook – to be shared in
an Azure Notebook
• Variables
• Conditional Structures
• Loops
• Functions
• Exception Handling
• Azure Notebook Library:
https://notebooks.azure.com/cletechconsulting/libraries/
introtopyforcsharpdevs
• More complex code using Visual Studio Community Edition
with the Python Tools and/or Visual Studio Code
• GitHub repo:
https://github.com/sadukie/IntroToPyForCSharpDevs
What version of Python am I running?
Location Command
Command-line python -V
Within a Python
environment
import sys
sys.version
Key Points from Python Style Guide (PEP 8)
• Indentation – 4 spaces
• Optional for continuation lines
• Make it readable and clearly identifiable
• If tabs are already in use, continue with tabs
• Do not mix tabs and spaces!
• Maximum line length should be 79 characters
• Easy for side-by-side files
• Works well for code review situations
• Docstrings and comments should be limited to 72 characters
• Imports on separate lines, always at the top
• Be consistent with quoting – single-quoted and double-quoted strings are the same.
• Read more at https://www.python.org/dev/peps/pep-0008/#imports
DEMO: Basics of Python
If Internet is present: Azure Notebooks
If Internet is not present: Jupyter Notebooks
Object-
Orientation
and Python
Classes, Methods, Dunders, and More!
Object Orientation
• Object oriented from the beginning
• Classes with:
• Data members (class variables and instance variables)
• Methods
• Class Variables vs Instance Variables
• Class variables are accessed for all instances of a class
• Within a class, outside of methods
• Not common
• Instance variables are managed by the instance
Inheritance
• Can inherit from multiple classes
• Can check relationships with isinstance() and issubclass()
• Parent class is accessed via super() method call
• Typical to call parent’s __init__() from within child’s __init__() before
moving on in the child’s initialization method
• Child knows about parents through its __bases__attribute
Interfaces
• Not necessary in Python
• No interface keyword in Python
• Try to invoke a method we expect
• Exception handling
• hasattr checking
• Duck typing
If it talks and walks like a duck, then it is a duck
Metaclasses
• Things typically defined in the language specification in other
languages
• Classes’ classes
• Class factories!
• Can be stored in a __metaclass__ attribute
• Can also be declared with metaclass= in the class declaration, following
parameters
• Most classes have the metaclass of type
• Traverse the __class__ tree enough, and you’ll end at type
Abstract Base Classes
• ABCs!
• abc module
• ABCMeta metaclass
• Use the pass keyword to not define the method’s body
• Must also use the @abc.abstractmethod decorator
• Can register classes as virtual subclasses of ABCs
• Only useful for categorization
• Does not know anything about its parent – nothing in __bases__
• Can throw errors if methods aren’t implemented
DEMO: Inheritance and ABCs
Magic Methods (Dunder
Methods)
Magic Methods
• Key concept to understand for OO Python
• Method names are surrounded by double underscores (“dunders”)
• Sometimes called dunder methods
• Object’s lifespan in magic methods
• __new__ - redefined rarely; used to create new instances; phase 1 of the
constructor
• __init__ - initializer for the class; passed the instance; most commonly used in
Python class definitions
• __del__ - the destructor; no guarantee that __del__ will be executed
Primary Uses for Magic Methods
• Constructors / Destructors
• Operator handling for Object types
• Comparison
• Unary Operators
• Extended Operators
More Magic Methods
• Comparison
• __eq__ - ==
• __ne__ - !=
• __lt__ - <
• __gt__ - >
• __le__ - <=
• __ge__ - >=
• Important keywords with these
• self – this instance
• other – instance to compare to
Other Applications of Python
Desktop Application Development
• Tkinter (“Tk
interface”) – Defacto
GUI creation in
Python for writing
desktop apps based
on Tcl/Tk
• PyQt – Python
package for writing
desktop apps based
on Qt
• If you prefer GTK:
• PyGObject
• pygtk
http://www.pygame.org
https://kivy.org
Web Frameworks
https://trypyramid.com/
https://www.djangoproject.com/
http://www.turbogears.org/
http://flask.pocoo.org
Testing
https://docs.pytest.org
https://pypi.org/project/behave/
http://lettuce.it/
Data Science
https://pandas.pydata.org/
https://matplotlib.org/
https://www.datacamp.com/
Taken from my Jupyter Notebook DataCamp notes…
SQL Server 2017 & Machine Learning
• Run Python in the server
• Brings computation to the data
• revoscalepy: https://docs.microsoft.com/en-us/machine-learning-
server/python-reference/revoscalepy/revoscalepy-package
Learn More!
• Seminar of Machine Learning in Python – Open Source Hong Kong –
led by Delon Yau, Software Engineer, Microsoft -
https://www.meetup.com/opensourcehk/events/251121245/
• Getting Started with Python in Visual Studio Code:
https://code.visualstudio.com/docs/python/python-tutorial
• Python Tools for Visual Studio:
https://www.visualstudio.com/vs/features/python/
• Python at Microsoft blog:
https://blogs.msdn.microsoft.com/pythonengineering/
Contact Information
• Twitter: @sadukie
• GitHub: sadukie
• LinkedIn:
https://linkedin.com/in/sadukie
• Email:
sarah@cletechconsulting.com

Intro to Python for C# Developers

  • 1.
  • 2.
    A C# Dev’sGuide to Python Presented by: Sarah Dutkiewicz Microsoft MVP, Visual Studio and Development Technologies Microsoft Developers HK 13 June, 2018
  • 3.
    About the Presenter •9 time Microsoft Most Valuable Professional – 2 years in Visual C#, 7 years in Visual Studio and Development Tools • Bachelor of Science in Computer Science & Engineering Technology • Published author of a PowerShell book • Live coding stream guest on Fritz and Friends and DevChatter • Why Hong Kong? #ancestraltrip!
  • 4.
    The Python Community Python’scommunity is vast; diverse & aims to grow; Python is Open. https://www.python.org/community/
  • 5.
    Diversity in Python ThePython Software Foundation and the global Python community welcome and encourage participation by everyone. Our community is based on mutual respect, tolerance, and encouragement, and we are working to help each other live up to these principles. We want our community to be more diverse: whoever you are, and whatever your background, we welcome you. https://www.python.org/community/diversity/
  • 6.
    The Zen ofPython, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. 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. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! https://www.python.org/dev/peps/pep-0020
  • 7.
    Areas Using Python •Analysis • Computation • Math • Science • Statistics • Engineering • Deep Learning • Artificial Intelligence • Machine Learning • Data Science
  • 8.
    Weakness of Python •The Great Python Schism • Hard version split between 2.x and 3.x • Some people are stuck on 2.x due to dependencies following the 2.x line • Greatly opinionated There should be one-- and preferably only one --obvious way to do it.
  • 9.
    Why Python 3? •Python 2 struggles with text and binary data • ‘abcd’ is both a string consisting of letters (textual) and a string consisting of bytes (binary) • Goes against the “preferably one way” part of the Zen of Python • Doesn’t do well with Unicode • Python was out before Unicode was a standard • Not all projects in Python 2 support Unicode equally • Python 3 • unicode/str/bytes types • Backwards-incompatible – but very much necessary, as Python is a language of the world
  • 10.
    Python Enhancement Proposals(PEPs) • https://www.python.org/dev/peps/ • Purpose and Guidelines for PEPs • Guidelines for Language Evolution • Deprecation of Standard Modules • Bug Fixes • Style Guides • Docstring Conventions • API for crypto • API for Python database • Python release schedules • … and more!
  • 11.
    Other Terms… • BenevolentDictator for Life (BDFL) – Guido van Rossum, father of Python • Pythonista – Python developer • Pythonic – code follows common guidelines, written in idiomatic Python • Pythoneer – pioneers of Python, leaders who create change • A Pythoneer can be a Pythonista, but not all Pythonistas are Pythoneers.
  • 12.
    Some Tools toKnow • Visual Studio with Python Tools • Visual Studio Code • Azure Notebooks • Repl.it • Jupyter Notebooks • PyCharm
  • 13.
    Package Management • ThinkNuGet only for Python • Pip (Pip Installs Packages) • Python’s official package manager • Virtualenv • Install pip packages in an isolated manner • Conda – conda.io • Not Python-specific – a cross-platform option similar to apt and yum • Part of Miniconda • Just conda and its dependencies • Also part of Anaconda • Conda, its dependencies, and many packages helpful in data science applications • More than one? Isn’t this anti-Zen? Yes, but… http://jakevdp.github.io/blog/2016/08/25/co nda-myths-and-misconceptions/
  • 14.
    Presentation Breakdown • SimplePython demos in a Jupyter Notebook – to be shared in an Azure Notebook • Variables • Conditional Structures • Loops • Functions • Exception Handling • Azure Notebook Library: https://notebooks.azure.com/cletechconsulting/libraries/ introtopyforcsharpdevs • More complex code using Visual Studio Community Edition with the Python Tools and/or Visual Studio Code • GitHub repo: https://github.com/sadukie/IntroToPyForCSharpDevs
  • 15.
    What version ofPython am I running? Location Command Command-line python -V Within a Python environment import sys sys.version
  • 16.
    Key Points fromPython Style Guide (PEP 8) • Indentation – 4 spaces • Optional for continuation lines • Make it readable and clearly identifiable • If tabs are already in use, continue with tabs • Do not mix tabs and spaces! • Maximum line length should be 79 characters • Easy for side-by-side files • Works well for code review situations • Docstrings and comments should be limited to 72 characters • Imports on separate lines, always at the top • Be consistent with quoting – single-quoted and double-quoted strings are the same. • Read more at https://www.python.org/dev/peps/pep-0008/#imports
  • 17.
    DEMO: Basics ofPython If Internet is present: Azure Notebooks If Internet is not present: Jupyter Notebooks
  • 18.
  • 19.
    Object Orientation • Objectoriented from the beginning • Classes with: • Data members (class variables and instance variables) • Methods • Class Variables vs Instance Variables • Class variables are accessed for all instances of a class • Within a class, outside of methods • Not common • Instance variables are managed by the instance
  • 20.
    Inheritance • Can inheritfrom multiple classes • Can check relationships with isinstance() and issubclass() • Parent class is accessed via super() method call • Typical to call parent’s __init__() from within child’s __init__() before moving on in the child’s initialization method • Child knows about parents through its __bases__attribute
  • 21.
    Interfaces • Not necessaryin Python • No interface keyword in Python • Try to invoke a method we expect • Exception handling • hasattr checking • Duck typing If it talks and walks like a duck, then it is a duck
  • 22.
    Metaclasses • Things typicallydefined in the language specification in other languages • Classes’ classes • Class factories! • Can be stored in a __metaclass__ attribute • Can also be declared with metaclass= in the class declaration, following parameters • Most classes have the metaclass of type • Traverse the __class__ tree enough, and you’ll end at type
  • 23.
    Abstract Base Classes •ABCs! • abc module • ABCMeta metaclass • Use the pass keyword to not define the method’s body • Must also use the @abc.abstractmethod decorator • Can register classes as virtual subclasses of ABCs • Only useful for categorization • Does not know anything about its parent – nothing in __bases__ • Can throw errors if methods aren’t implemented
  • 24.
  • 25.
  • 26.
    Magic Methods • Keyconcept to understand for OO Python • Method names are surrounded by double underscores (“dunders”) • Sometimes called dunder methods • Object’s lifespan in magic methods • __new__ - redefined rarely; used to create new instances; phase 1 of the constructor • __init__ - initializer for the class; passed the instance; most commonly used in Python class definitions • __del__ - the destructor; no guarantee that __del__ will be executed
  • 27.
    Primary Uses forMagic Methods • Constructors / Destructors • Operator handling for Object types • Comparison • Unary Operators • Extended Operators
  • 28.
    More Magic Methods •Comparison • __eq__ - == • __ne__ - != • __lt__ - < • __gt__ - > • __le__ - <= • __ge__ - >= • Important keywords with these • self – this instance • other – instance to compare to
  • 29.
  • 30.
    Desktop Application Development •Tkinter (“Tk interface”) – Defacto GUI creation in Python for writing desktop apps based on Tcl/Tk • PyQt – Python package for writing desktop apps based on Qt • If you prefer GTK: • PyGObject • pygtk http://www.pygame.org https://kivy.org
  • 31.
  • 32.
  • 33.
  • 34.
    Taken from myJupyter Notebook DataCamp notes…
  • 35.
    SQL Server 2017& Machine Learning • Run Python in the server • Brings computation to the data • revoscalepy: https://docs.microsoft.com/en-us/machine-learning- server/python-reference/revoscalepy/revoscalepy-package
  • 36.
    Learn More! • Seminarof Machine Learning in Python – Open Source Hong Kong – led by Delon Yau, Software Engineer, Microsoft - https://www.meetup.com/opensourcehk/events/251121245/ • Getting Started with Python in Visual Studio Code: https://code.visualstudio.com/docs/python/python-tutorial • Python Tools for Visual Studio: https://www.visualstudio.com/vs/features/python/ • Python at Microsoft blog: https://blogs.msdn.microsoft.com/pythonengineering/
  • 37.
    Contact Information • Twitter:@sadukie • GitHub: sadukie • LinkedIn: https://linkedin.com/in/sadukie • Email: sarah@cletechconsulting.com

Editor's Notes

  • #3 Abstract: As technology continues to evolve, our toolset as developers evolves as well. While we can use C# for many things, other languages are growing in popularity in other areas - such as Python being used in AI, ML, and other aspects of data science. In this session, we will see how we do things in Python compared to what we do in C#. Some of the tools we will look at include Anaconda with Visual Studio Code and Visual Studio's Python tooling.
  • #10 * Source: Why Python 3 Exists - https://snarky.ca/why-python-3-exists/