DAP event
e
CUSP
Writing Idiomatic Python;
Python Packaging;
Static Website Generator;
-Mohit Sharma
http://slides.com/mohitsharma44/deck/live
Idiomatic python
Why ?
>>> import this
How ?
Stay tuned...
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
- John Woods
Lets get started..
A Word of Advice
if language == "Python" or language == "Shell" or language == "Java" or language == "C++":
print("""
For the brave souls who get this far: You are the chosen ones,
the valiant knights of programming.
""")
if language in ("Python", "Shell", "Java", "C++"):
print("""
For the brave souls who get this far: You are the chosen ones,
the valiant knights of programming.
""")
Multiple Condition Checking
def some_useful_print_function(car):
return "Company: "+car.company + "Name: "+car.name + \
"Type: "+car.type + "Year: "+car.year + "Price: "\
+car.price
def some_useful_print_function(car):
return "Company: %s " + "Name: %s "+ "Type: %s " + "Year: %d " +\
"Price: %f " %(car.company, car.name, car.type, car.year,
car.price)
def some_useful_print_function(car):
return "Company: {vehicle.company} " + "Name: {vehicle.name} "+ \
"Type: {vehicle.type} " + "Year: {vehicle.year} " + \
"Price: {vehicle.price} ".format(vehicle=car)
result = None
for value in values:
if acceptable(value):
result = value
break
if not result:
raise ValueError("No acceptable language found!")
result = None
for value in values:
if acceptable(value):
result = value
break
else:
raise ValueError("No acceptable language found!")
for ... else
for i in range(1000000):
...
for i in xrange(1000000):
...
Looping over range of numbers
fruits = ["apples", "mangoes", "banana"]
for i in range(len(fruits)):
print fruits[i]
fruits = ["apples", "mangoes", "banana"]
for fruit in fruits:
print fruit
Looping over a collection
fruits = ["apples", "mangoes", "banana"]
for i in range(len(fruits)):
print i, ' = ', fruits[i]
fruits = ["apples", "mangoes", "banana"]
for i, fruit in enumerate(fruits):
print i, ' = ', fruit
Looping over collection and indices
Looping over two collections
colors = ["red", "blue", "green", "yellow"]
fruits = ["apples", "mangoes", "banana"]
# Take min of two collections and loop over the smallest:
n = min(len(colors), len(fruits))
for i in range(n):
print fruits[i], " = ", colors[i]
# It creates a 3rd list that consists of tuples
# which consists its own set of objects
# that points back to the actual list
for fruit, color in zip(fruits, colors):
print fruit, " = ", color
# iterator for zip
from itertools import izip
for fruit, color in izip(fruits, colors):
print fruit, " = ", color
fruits = ["apples", "mangoes", "banana"]
for fruit in sorted(fruits):
print fruit
# Reversed
for fruit in sorted(fruits, reverse=True):
print fruit
fruits = ["apples", "mangoes", "banana"]
# In place list sorting
fruit.sort()
# Reversed
fruit.sort(reverse=True)
sorting a list
fruits = ["apples", "mangoes", "banana"]
result = ""
for fruit in fruits:
result += fruit + " "
fruits = ["apples", "mangoes", "banana"]
result = " ".join(fruits)
String from a List
fruits = ["apples", "mangoes", "banana"]
fruit = "apples"
if fruit not in fruits:
fruits.append(fruit)
fruits = set(["apples", "mangoes", "banana"])
fruit = "apples"
fruits.append(fruit)
Sets
fruits = ["apples", "mangoes", "banana"]
fruit = "apples"
if fruit not in fruits:
fruits.append(fruit)
fruits = set(["apples", "mangoes", "banana"])
fruit = "apples"
fruits.append(fruit)
Sets
# Removing an element
for k in d.keys():
if k.startswith('r'):
del d[k]
d = {k: d[k] for k in d if not k.startswith('r')}
Looping over dictionary keys
d = dict(izip(fruits, colors))
Construct a dictionary from multiple sequences
from collections import defaultdict
colors = ["red", "blue", "green", "yellow"]
d = defaultdict(int)
for color in colors:
d[name] += 1
Counting in dictionaries
from collections import defaultdict
colors = ["red", "blue", "green", "amber", "gray"]
d = defaultdict(list)
for color in colors:
key = len(color)
d[key].append(color)
Grouping in dictionaries
try:
os.remove('somefile.tmp')
except OSError, e:
print "Watchout, Man! \n"+str(e)
@contextmanager
def ignored(*exception):
try:
yield
except exception, e:
print "Watchout, Man! \n"+str(e)
with ignored(OSError):
os.remove('somefile.tmp')
Context Managers
# List Comprehension
sum([i**2 for i in xrange(10)])
# List Comprehension
sum(i**2 for i in xrange(10))
Generator Expressions
A word of Caution
# Dear maintainer:
# Once you are done trying to 'optimize' this
# routine,and have realized what a terrible
# mistake that was, please increment the
# following counter as a warning to the next
# guy:
#
# total_hours_wasted_here = 42
Premature optimization is the root of all evil
Python Packaging
from init to deploy
...made easy
Setting up your environment
* Project X requires numpy v1.5.0 because it is using
numpy.refft
* Project Y requires numpy v1.6.0 because it is using
numpy.fft
* Install packages without root privileges.
Virtualenv !!!
Setting up your environment
$ mkdir venv
$ virtualenv venv
* Install virtualenv
$ pip install virtualenv
* Create a virtual environment
$ source venv/bin/activate
* Activate virtualenv
(venv)$ deactivate
* Restore environment
* Check your installed packages
$ pip freeze
Structure of a python package
my_package
setup.py
my_package
tests
docs
__init__.py
__init__.py
__init__.py
__init__.py
test_module1.py
conf.py
subpackage
module1.py
Pyscaffold
* Install pyscaffold
(venv)$ pip install pyscaffold
* You can also install a particular version (optional)
(venv)$ pip install "pyscaffold>=2.4"
* Install sphinx
(venv)$ pip install sphinx
Time for demo!
Generating Static Website
Pelican
(venv)$ pelican-quickstart
* Install markdown
(venv)$ pip install markdown
* quickstart
* Install pelican
(venv)$ pip install pelican
first_post
##########
:date: 2016-04-21 13:32
:category: Test
Hello World from Pelican!
* Your first post
> Where do you want to create your new web site? [.]
> What will be the title of this web site? cusp-edap
> Who will be the author of this web site? mohit
> What will be the default language of this web site? [en]
> Do you want to specify a URL prefix? e.g., http://example.com (Y/n)
> What is your URL prefix? (see above example; no trailing slash) http://localhost:8000
> Do you want to enable article pagination? (Y/n)
> How many articles per page do you want? [10]
> What is your time zone? [Europe/Paris] America/NewYork
Please enter a valid time zone:
(check [http://en.wikipedia.org/wiki/List_of_tz_database_time_zones])
> What is your time zone? [Europe/Paris] America/New York
> Do you want to generate a Fabfile/Makefile to automate generation and publishing? (Y/n) n
> Do you want an auto-reload & simpleHTTP script to assist with theme and site development? (Y/n)
* Questionaire
Publishing on github pages
* Remove all files from the old working tree
(venv)$ git rm -rf .
* copy output to gh-pages branch, commit and push
* checkout another branch
(venv)$ git checkout --orphan gh-pages
* Checkout to master and merge gh-pages
(venv)$ git checkout master
(venv)$ git merge gh-pages
(venv)$ git push origin master
cusp-edap
By mohit sharma
cusp-edap
- 2,702