Python for the C# developer

 
Table of Contents:

Agenda

  • Introduce the basic of the Python language
  • Review what is awsome about C# and .NET
  • Explorer Python's version of each C# / .NET feature
 

The Python language in 10 minutes

  • High-level programming language
  • Batteries included (large standard library)
  • Interpreted (sometime JIT compiled)
  • Object-oriented (especially Python 3)
  • Strongly-typed with dynamic semantics
  • Syntax emphasizes readibity
  • Supports reuse through modules and packages
 

The 'shape' of a Python program

  • Python defines code blocks (known as suites in Python) using white space and colons.
    • def somemethod(name): if name == "Michael": print("Hi old friend") else: print("Nice to meet you") print("My name is ...") def main(): somemethod()
  • Pytnon language Demo
    • # wather.py import random # public List<String> GetDays() def get_days(): # List<String> days = new List<String>(); days = [] days = ['mon', 'tues', 'wed', 'thurs', 'fri', 'sat', 'sun'] return days def get_random_report(): weather = ['sunny', 'lovely', 'cold'] return weather[random.randint0, len(weather)-1] def main(): days = get_days() for day in days: report = get_random_report() print("On {0} it will be {1}.".format(day, report) if __name__ == "__main__": main()
       

What's awesome about C# and .NET?

  • System.Object Everything is an Object
  • IEnumerable + foreach loops
  • Class properties(int Age {get; set;})
  • Anonymous Type
  • Add reference
  • NuGET package management
  • Entity Framework / ORMs
  • Great debugging tools
  • LINQ
  • Visual Studio } IDEs
  • Side-by-side execution(isolation)
  • Iterator methods } yeild return
  • Anonymous methods / lamdas / closures
  • Base class libraries
  • JIT compilation
  • Resharper and IDE plugins
  • GUI designer
 

IDEs

  • C#
    • Visual Sutdio
  • Python
    • PyCharm
 

Great Debugger

  • C#
  • Python
  • All is beatiful
 

Everything is an Object

  • C#
    • class Document : object { public void Serialize() { // ... } public override string ToString() { return "I am a document"; } }
       
  • Python
    • class Document( object ): def serialize(self): # ... def __str__(self): return "I am a document."
 

IEnumerable + foreach loops

  • C#
    • int[] numbers = new[] {1, 2, 3, 4, 5, 6}; foreach (var n in numbers) { Console.write(n + ","); }
  • Python
    • nums = [2, 3, 5, 7, 11, 13, 17, 19] for n in nums: print(n, end=', ')
      nums = [2, 3, 5, 7, 11, 13, 17, 19] for v in enumerate(nums): print(v, end=', ')
      nums = [2, 3, 5, 7, 11, 13, 17, 19] for index,n in enumerate(nums): print(n, end=', ')
 
  • C#
    • class ShoppingCart : IEnumerable<Tuple<string, float>> { List<Tuple<string, float>> cartItems = new List<Tuple<string, float>>(); public void Add(string name, float price) { cartItems.Add(new Tuple<string, float>(name, price)); } public IEnumerable<Tuple<string, float>> GetEnumerator() { return cartItems.GetEnumerator(); } IEnumerator IEnumeratable.GetEnumerator() { return GetEnumerator(); } }
  • Python
    • class CartItem: def __init__(self, name, price): self.name = name self.price = price def __repr__(self): return "{0}, ${1}".format(self.name, self.price) class ShoopingCart: def __init__(self): self.__items = [] def add(self, cart_item): self.itmes.append(cart_item) def __iter__(self): return self.__itmes.__iter__() cart = ShoppingCart() cart.add(CartTiem("CD", 19.99) cart.add(CartTiem("Record", 17.99) for item in cart.items: print(iteem)
 

Properties

  • C#
    • class ShoppingCart : IEnumerable<Tuple<string, float>> { List<Tuple<string, float>> cartItems = new List<Tuple<string, float>>(); public void Add(string name, float price) { cartItems.Add(new Tuple<string, float>(name, price)); } public IEnumerable<Tuple<string, float>> GetEnumerator() { return cartItems.GetEnumerator(); } IEnumerator IEnumeratable.GetEnumerator() { return GetEnumerator(); } } class ShoppingCart { get { float total = 0; foreach (var item in cartItems) { total += item.price; } return total; } } Console.WriteLine("Total price: {0}", cart.TotalPrice);
  • Python
    • class CartItem: def __init__(self, name, price): self.name = name self.price = price def __repr__(self): return "{0}, ${1}".format(self.name, self.price) class ShoopingCart: def __init__(self): self.__items = [] def add(self, cart_item): self.itmes.append(cart_item) def __iter__(self): return self.__itmes.__iter__() @property def total_price(self): total = 0.0 for item in self.__items: total += item.price return total cart = ShoppingCart() cart.add(CartTiem("CD", 19.99) cart.add(CartTiem("Record", 17.99) for item in cart.items: print(iteem) print("Total price is {0:,", cart.total_price()}
       

Anonymous objects

  • C#
    • var o = new { id = 2, Registered = true }; Console.WriteLine(o); if (o.Registered) { Console.WriteLine("They are registered..."); }
 
  • Python
    • class AnonObject(dict): __getattr__ = dict.get __setattr__ = dict.__setitem__ o = AnonObject(id = 42; registered = true) print(o) if o.registered: print("They are registered...")
       

Lambda expression

  • C#
    • private static IEnumerable<int> FindNumbers(Predicate<int> predicate) { for (int i = 0; i < 100; i++ { if (predicate(i)) yield return i; } } IEnumerable<int> nums = FindNumbers(n => n % 11 == 0)
 
  • Python
    • def numFilter(predicate): for i in range(100): if predicate(i): yield i nums = numFilter(lambda n : n % 11 == 0)
       
      def get_numbers(limit, predicate): for n in range(0, limit): if predicate(n): yield n # def divide_by_11(n): # return n % 11 = output = list(get_numbers(40, lambda n: n % 11 == 0)) print(output)
       

LINQ

  • C#
    • var older in people where p.age > 30 orderedby p.age descending select new {age = p.age, name = p.name}
  • Python
    • class Person: def __init__(self, name, age, hobby): self.name = name self.age = age self.hobby = hobby def __repr__(self): return "{0} is {1} and {likes {2}".format(self.name, self.age, self.hobby) people = [ Person("Jeff", 50, "Biking"), Person("Michael", 40, "Biking"), Person("Sarah", 30, "Running"), Person("Tony", 24, "Jogging"), Person("Zoe", 12, "TV") ] bikers = [ p for p in people if p.hobby == "biking" ] biker.sort(key = lambda p: p.name for b in bikers: print(b)
       

NuGET package management

  • C#
    • Install-Package mongocsharpdriver
  • Python
    • pip install pymongo
 

Iterator methods / yield return

  • C#
    • private static IEnumerable<int> FibonacciGenerator() { int current = 1; int next = 1; yield return current; while (true) { int temp = current + next; current = next; next = temp; yield return current; } }
       
  • Python
    • def fibonacci_generator(): current, nxt = 1, 1 yield current while True: current, nxt = nxt, current + nxt yield current
       
      def fibonacci(): current = 0 nxt = 1 while True: current, nxt = nxt, current + nxt yield current for n in fibonacci(): if n > 200: break print(n, end=', ')
       

ASP.NET MVC

  • C#
    • ASP.NET
  • Python
    • Pyramid
    • django
    • Flask
    •  

Entity Framework

  • C#
    • .net Entity Framework
  • Pythhon
    • SQL Alchemy
 

JIT compilation

  • C#
    • JIT compliation via CLR
  • Python
    • pypy
    • IronPython
      • .NET Python on CLR
    • Jython
      • Java Python on JVM
 

GUI Desginer

  • C#
    • Visual Studio
  • Python
    • PyQT (QT framework)
    •  

Summary: Python for C# developer

  • Python language is simple, concise and reable
  • Many parts of C# and .NET are awesome
  • Python often has equivalent features
    • sometimes nicer
    • sometimes less nice
  • Python has very capable IDE / Debugger in PyCharm
 

Q&A

  • Why use snake_case in Python?
    • It's Pythons' convention.
    • UpperCamelCase: class and many types...
    • snake_case: method and variables....