Skip to content

Instantly share code, notes, and snippets.

@japboy
Created December 10, 2009 10:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save japboy/253252 to your computer and use it in GitHub Desktop.
Save japboy/253252 to your computer and use it in GitHub Desktop.
some python study coding snippets
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Python Date & Time
Usage of datetime library (INCOMPLETE)
"""
from datetime import datetime, timedelta
dt = datetime.datetime(2009,1,1,23,59)
dt + timedelta(days=3)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""JSON and Python
@see http://gihyo.jp/dev/serial/01/pythonhacks/0011
"""
from datetime import datetime
try:
import json
except ImportError:
import simplejson as json
# Pass Python object to JSON string
obj = list(range(10))
str = json.dumps(obj)
print(type(str), str)
# Pass JSON string to Python object
obj = json.loads(str)
print(type(obj), obj)
# Override JSONEncoder for DateTime encoding
class DateTimeEncoder(json.JSONEncoder):
pass
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Socket HTTP server & client reimplementation
This is sample script to study how Socket works and
how HTTP is proceeded.
"""
from select import select
import socket
import sys
from time import sleep
ADDR = ('localhost', 8080)
class HTTPClient(object):
"""HTTP client class
One thing really important is that there's no EOT in socket.
If send or recv returns 0, the network is broken.
A client class has two jobs. One is offering send and recv to
a server class. Another is just as a client software.
"""
def __init__(self, s=None):
if not s:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
else:
self.s = s
def connect(self, addr=ADDR):
self.s.connect(addr)
def send(self, msg):
msglen = len(msg)
sent = 0
while sent < msglen:
sent_bytes = self.s.send(msg[sent:])
if sent_bytes == 0:
raise RuntimeError('socket connection broken')
sent += sent_bytes
def recv(self, byte_size=525, ans=None):
msg = ''
while True:
try:
buf = self.s.recv(byte_size)
msg += buf
if msg == ans:
print msg
break
except (KeyboardInterrupt, SystemExit), e:
print e
break
def close(self):
self.s.close()
class HTTPServer(object):
"""HTTP server class
A server socket only produces client sockets (client_sock) and
each client socket does send and recieve data.
A server class needs a client class as well.
"""
def __init__(self):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def bind(self, addr=ADDR):
self.s.bind(addr)
def listen(self, max_requests=5):
self.s.listen(max_requests)
def accept(self):
while True:
try:
(client_sock, addr) = self.s.accept()
client = HTTPClient(client_sock)
print 'sending to', addr[0], addr[1]
client.send('Hello world.')
print 'closing a client...'
client.close()
except (KeyboardInterrupt, SystemExit), e:
print e
break
def close(self):
self.s.close()
def run_test_server():
server = HTTPServer()
print 'binding...'
server.bind()
print 'listening...'
server.listen()
print 'accepting...'
server.accept()
print 'closing...'
server.close()
print 'all done.'
def run_test_client():
client = HTTPClient()
print 'connecting...'
client.connect()
print 'recieving...'
client.recv(2, 'Hello world.')
print 'closing...'
client.close()
if __name__ == '__main__':
if sys.argv[1] == '-s':
run_test_server()
elif sys.argv[1] == '-c':
run_test_client()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""WSGI Hello World
Script running on its built-in server
"""
from wsgiref import simple_server
def runWebApp(env, response):
response('200 OK', [('Content-type', 'text/plain')])
return 'Hello, world'
if __name__ == '__main__':
server = simple_server.make_server('', 8080, runWebApp)
server.serve_forever()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Let CherryPy say hello on Google App Engine"""
import wsgiref.handlers
import cherrypy
class Root():
@cherrypy.expose
def index(self):
return 'Hello, world.'
def main():
app = cherrypy.tree.mount(Root(), '/')
wsgiref.handlers.CGIHandler().run(app)
if __name__ == '__main__':
main()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Basis of Python arbitrary argument lists"""
def test_tuple_args(*args):
print 'The argument type:', type(args)
for arg in args:
print arg
def test_dict_args(**kwargs):
print type(kwargs)
for key in kwargs:
print key, kwargs[key]
def test_both_args(*args, **kwargs):
pass
def run_tests():
test_tuple_args()
test_dict_args()
if __name__ == '__main__':
run_tests()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Basis of Python: Built-in objects
* String
* List
* Dictionary
* Tuple
* File
"""
__author__ = 'Yu Inao'
class SequenceTester(object):
"""Sequence object class
Python objects has some types. The type of String, List, and
Tuple objects are called Sequence.
This class checks what Sequence can do.
"""
def __init__(self, obj):
if type(obj) == 'list' or 'string' or 'tuple':
self.sequence = obj
print self.sequence
else:
raise Exception, 'The argument type must be sequence.'
return
def get_length(self):
"""Return length"""
return len(self.sequence)
def get_particular_value(self, index=0):
"""Return value of particular index number"""
return self.sequence[index]
def get_sliced_value(self, first=None, last=None):
"""Return sliced value from specified range"""
if first and last:
sliced_value = self.sequence[first:last]
elif first:
sliced_value = self.sequence[first:]
elif last:
sliced_value = self.sequence[:last]
else:
sliced_value = self.sequence[:]
return sliced_value
def set_overridden_value(self, index=0, value=''):
"""Try to set new value to existed object
This is to check whether the object is immutable or not.
"""
try:
self.sequence[index] = value
except TypeError, e:
print 'Immutable objects cannot be overridden:', e
return
class MappingTester(object):
"""Map object class
The type of Dictionary object is called Map.
This class checks what Map can do.
"""
def __init__(self, obj):
if type(obj) == 'dict':
self.map = obj
else:
raise Exception, 'The argument type must be map.'
return
def get_value_by_key(self, key):
return self.map[key]
class StringTester(SequenceTester):
"""String object class
This class checks what exactly String can do.
There are actually more methods for String.
"""
def find(self, match=''):
return self.sequence.find(match)
def replace(self, match='', replace=''):
return self.sequence.replace(match, replace)
def split(self, separator=','):
"""Return String as List by separater value"""
return self.sequence.split(separator)
class ListTester(SequenceTester):
def append(self, element):
self.sequence.append(element)
def pop(self, index):
self.sequence.pop(index)
#del self.sequence[index]
class DictionaryTester(object):
def __init__(self):
pass
if __name__ == '__main__':
string_test = StringTester('This is a string and it is ' + \
'a part of sequence objects.')
print string_test.get_length()
print string_test.get_particular_value(-8)
print string_test.get_sliced_value(5, -18)
string_test.set_overridden_value('bla bla')
print string_test.find('part')
print string_test.replace('string', 'STRING')
for test in string_test.split(' '):
print test
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Basis of Python Closure"""
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Basis of Python Decorator"""
def decorate(function):
"""Decolator function:
This decorator overrides original 'function' and
returns 'wrap_function'.
"""
def wrap_function(*args, **kwargs):
"""Wrapper function:
This wrapper receives arguments of 'function' and
returns additional messeage with original 'function'.
"""
print 'Hello from decorated %s.' % function.__name__
obj = function(*args, **kwargs)
return obj
return wrap_function
def decorate_with_arg(str):
"""Decorator function with arguments:
This decorator receives an argument 'str' and
returns 'decorate' function like as mentioned above.
"""
def decorate(function):
"""Decorator function:
This decorator overrides original 'function' and
returns 'wrap_function'.
"""
def wrap_function(*args, **kwargs):
"""Wrapper function:
This wrapper receives arguments of 'function' and
returns additional messeage including decorator's
argument with original 'function'.
"""
print 'Hi %s from decorated %s' % (str, function.__name__)
obj = function(*args, **kwargs)
return obj
return wrap_function
return decorate
@decorate
def test_decorator(name):
"""Decorated function:
This function just shows a message with the argument.
**Recommended way to be decorated**
"""
print 'Hey %s from decorating %s.' % (name, test_decorator.__name__)
def test_alt_decorator(name):
"""Function:
This function just shows a message with the argument.
**Followed code is obsolete way to decorate this function**
"""
print 'Hey %s from decorating %s.' % (name, test_alt_decorator.__name__)
test_alt_decorator = decorate(test_alt_decorator)
@decorate
@decorate_with_arg('Anonymous')
def test_decorators():
"""Decorated function by 2 decorators:
This function just shows a messeage.
**Recommended way to be decorated by several decorators and
decorators having arguments**
"""
print 'Hiya %s.' % test_decorators.__name__
def test_alt_decorators():
"""Function:
This function just shows a messeage.
**Followed codes are obsolete way to decorate this function
with several decorators having arguments**
"""
print 'Hiya %s.' % test_alt_decorators.__name__
wrapper = decorate_with_arg('Doe')
test_alt_decorators = decorate(wrapper(test_alt_decorators))
def start_test():
"""Function:
This function just tests decorator functions and
decorated functions as declared above.
"""
# Run decorated functions
print '#1'
test_decorator('John')
print '#2'
test_alt_decorator('Coward')
print '#3'
test_decorators()
print '#4'
test_alt_decorators()
if __name__ == '__main__':
start_test()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u"""Study of list comprehensions (リスト内包表記)
* PEP 202 -- List Comprehensions
http://www.python.org/dev/peps/pep-0202/
* 5.2.4. List displays — Python documentation
http://docs.python.org/reference/expressions.html#list-displays
"""
import unittest
class ListComprehensions(unittest.TestCase):
def test_list(self):
numbers = range(10)
self.assertIsInstance(numbers, list)
self.assertEqual(len(numbers), 10)
i = 0
for number in numbers:
self.assertEqual(number, i)
# Prove `numbers` is `[0,1,2,3,4,5,6,7,8,9]`
i += 1
def test_list_with_for_statement(self):
numbers = range(10)
self.assertIsInstance(numbers, list)
self.assertEqual(len(numbers), 10)
new_numbers = [number for number in numbers]
# Same as `numbers`
self.assertIsInstance(new_numbers, list)
self.assertEqual(len(new_numbers), len(numbers))
for i in range(10):
self.assertEqual(numbers[i], new_numbers[i])
# Prove it
def test_list_with_for_and_if_statement(self):
numbers = range(10)
self.assertIsInstance(numbers, list)
self.assertEqual(len(numbers), 10)
new_numbers = [number for number in numbers if number % 2 == 0]
# Even numbers only from `numbers`
self.assertIsInstance(new_numbers, list)
self.assertEqual(len(new_numbers), 5)
i = 0
for j in range(5):
self.assertEqual(numbers[i + j], new_numbers[j])
# Prove it
i += 1
def test_complicated_list_for_and_for_statement(self):
numbers = range(10)
other_numbers = range(10)
self.assertIsInstance(numbers, list)
self.assertIsInstance(other_numbers, list)
self.assertEqual(len(numbers), 10)
self.assertEqual(len(other_numbers), 10)
pairs = [(number, another_number) \
for number in numbers for another_number in other_numbers \
if number == another_number]
# Make a list of tuple pairs like [(0,0),(1,1),(2,2)...]
self.assertIsInstance(pairs, list)
self.assertEqual(len(pairs), 10)
i = 0
for pair in pairs:
self.assertIsInstance(pair, tuple)
self.assertEqual(pair[0], i)
self.assertEqual(pair[1], i)
# Prove it
i += 1
if __name__ == u'__main__':
unittest.main(verbosity=2)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Basis of Python lists:
* List is mutable object
* Tuple is immutable object
* Dictionary is mutable object
* Iterator
"""
str = 'Hello'
list = [str, 0, 01.23, '01.23', 'Hey']
tuple = (str, 0, 01.23, '01.23', 'Hey')
dict = {'1st': str,
2: {str: 'hey',
'2-1': 100},
'3rd': 'bar'}
def begin_test():
print str
for obj in list:
print obj
for obj in tuple:
print obj
print 'Display Dictionary content:'
for key in dict:
print key, dict[key]
if __name__ == '__main__':
begin_test()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Basis of Python OOP"""
# TODO: Add sample of constructors
class Ball(object):
"""Class (that can be a super class):
Class is kind of a template of an object (aka instance),
and can be a class object(instance) once it's instantiated.
"""
def __init__(self, shape='sphere'):
"""Constructor:
This method is run when its class 'Ball' is instantiated,
and creates an attribute 'shape' for the class object.
"""
self.shape = shape
def pass_(self):
"""Instance method"""
print 'A ball is now passed.'
class SoccerBall(Ball):
"""Sub class inherited from Ball class:
This class has all of attribute and method of super class 'Ball'.
"""
def pass_(self, teammate):
"""Instance method:
This method overrides 'pass_' method of super class 'Ball'.
"""
print "Test4: " + \
'A soccer ball is now passed to %s.' % teammate
class Basketball(Ball):
"""Another sub class inherited from Ball class"""
@classmethod
def hold(cls, test6=False):
"""Class method:
@see http://www.python.jp/doc/2.4/lib/built-in-funcs.html
"""
if test6:
print 'Test6: A basketball is now being held.'
else:
print 'Test5: A basketball is now being held.'
def start_the_game():
"""Function:
This function tests classes as declared above.
"""
print 'Now starting the game!'
# **********
# Test 1a
# **********
try:
print 'Result: %s' % Ball.shape # Never be called
except Exception, e:
print 'Result: %s' % e
print "Is 'Ball' an instance of 'Ball': %s" % isinstance(Ball, Ball)
# **********
# Test 1b
# **********
try:
print 'Result: %s' % Ball().shape
except Exception, e:
print 'Result: %s' % e # Never be called
print "Is 'Ball()' an instance of 'Ball': %s" % isinstance(Ball(), Ball)
# **********
# Test 1a
# **********
print 'Test 1a:'
ball = Ball # Copy 'Ball' class to 'ball' variable
if isinstance(ball, Ball):
print "'ball' IS an instance of 'Ball'." # Never be called
else:
print "'ball' is NOT an instance of 'Ball'."
#print Ball.shape
print type(Ball().shape)
#print ball.shape
print ball().shape
# **********
# Test 1b
# **********
print 'Test 1b:'
ball = Ball() # Instantiate 'Ball' class to 'ball' variable
if isinstance(ball, Ball):
print "'ball' IS an instance of 'Ball'."
else:
print "'ball' is NOT an instance of 'Ball'." # Never be called
#print Ball.shape
print Ball().shape
print ball.shape
#print ball().shape
# **********
# Test 3
# **********
soccerball = SoccerBall
# Try to call an instance method of SoccerBall class
# as an soccerball variable's method
try:
soccerball.pass_('John') # Impossible as instance method
except TypeError, e:
print 'Test3: %s' % str(e)
# **********
# Test 4
# **********
soccerball = SoccerBall()
soccerball.pass_('John')
# **********
# Test 5
# **********
basketball = Basketball
basketball.hold() # Only possible as class method
# **********
# Test 6
# **********
basketball = Basketball()
basketball.hold(True)
# **********
# Test 7
# **********
Basketball().pass_() # Possible to directly call
# a class and the method
print Basketball().shape
x = Basketball
print x.shape
if __name__ == '__main__':
start_the_game()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""CherryPy Hello World
Script running on its built-in server
Just run below & check 'http://localhost:8080/':
$ python ./cherrypy.py
"""
import cherrypy
# Site config
cherrypy.config.update({'server.socket_host': '127.0.0.1',
'server.socket_port': 8080,})
# Application config
CONFIG = {'/': {'tools.gzip.on': True}}
class Root():
"""Declare a publishing object"""
@cherrypy.expose
def index(self):
"""Declare a method like RESTful"""
return 'Hello, world.'
# Run the built-in server deamon with a publishing object
cherrypy.quickstart(Root(), '/', config=CONFIG)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Just a crap of shit
"""
"""
What `if __name__ == '__main__':` means
@see http://ibiblio.org/g2swap/byteofpython/read/module-name.html
"""
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u"""Fundamental template module
This is my fundamental template writing Python codes. Currently based on
respective PEP 8, Rob Knight's Python Coding Guidelines, and Google Python
Style Guide.
* PEP 8 -- Style Guide for Python Code
http://www.python.org/dev/peps/pep-0008/
* Python Coding Guidelines
http://bayes.colorado.edu/PythonGuidelines.html
* Google Python Style Guide
http://google-styleguide.googlecode.com/svn/trunk/pyguide.html
"""
import sys
__author__ = u'Yu I.'
__copyright__ = u'Copyright 2011, Yu I.'
__credits__ = [u'Guido van Rossum',
u'Barry Warsaw',
u'Rob Knight',
u'Amit Patel',
u'Antoine Picard',
u'Eugene Jhong',
u'Jeremy Hylton',
u'Matt Smart,',
u'Mike Shields']
__license__ = u'Public domain'
__version__ = u'0.2'
__maintainer__ = u'Yu I.'
__email__ = u'anonymous@foo.bar'
__status__ = u'Experiment'
def hello():
"""Write 'Hello.' to standard output."""
sys.stdout.write('Hello.\n')
if __name__ == u'__main__':
hello()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PyQt
@see http://zetcode.com/tutorials/pyqt4/
"""
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
widget.resize(250, 150)
widget.setWindowTitle('simple')
widget.show()
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment