Reputation Top 1%
Miklós Prisznyák
24 Snippets  (28th place)
1 Channel
2 Channels
14206 points  (7th place)
Top 5% Publisher
Junior Code Generator
Serious Code Generator
Senior Code Generator
Junior Publisher
Serious Publisher
Senior Publisher
Junior Topic Creator
Junior Topic Hub
Serious Topic Hub
Junior Trend Maker
Serious Trend Maker
Junior Judge
Serious Judge
Junior Popular Coder
Serious Popular Coder
Senior Popular Coder
Master Popular Coder
Junior Autobiographer
Serious Autobiographer
Senior Autobiographer
Master Autobiographer
Junior Famous Coder
Master Famous Coder
Junior Wise Coder

Recent Snippets See all snippets by mprisznyak

public by mprisznyak  4998  3  5  4

Command pattern

Look ma, no objects!
# Command Pattern 
# using only functions which are "first-class citizen" in Python
# and therefore they can be passed around 

# do something actually
def say(msg):

# action functions
def meauw():

def woof():
def neigh():

# command -> action mapping
actions =  {
	"cat": meauw,
	"dog": woof,
	"horse": neigh,

def handle(command):
  the command executioner...
  whoohaahaa! :)
	action = actions.get(command,None)
	if action: # existing command
		action() # execute command
	else: # no command found
		say("Sorry! No %s here." % command) # no such command!

for cmd in ["cat", "horse", "dog", "elephant"]:

public by mprisznyak  2927  9  6  2

Counting specific elements in a list

The Bad, Ugly One and the Good, Beautiful One
# data
test = [1,3, 'a', 'a', 1, 1, 'b', 'a']            

# the wrong way
count = 0
for item in test:
    if item == 'a': count += 1
print("The number of 'a's is {}".format(count)) 

# the right way
print("The number of 'a's is {}".format(test.count('a'))) 

public by mprisznyak  4130  4  6  2

Command design pattern

A generic implementation for the Command design pattern It's demonstrated by two toy examples: 1/ a lamp which can be turned on and off 2/ a car which can be started up, filled up with petrol and driven. Some commands have parameters in this example.
# -*- coding: utf-8 -*-
Command design pattern

class Command(object):
    """ generic command class
    def __init__(self, action, target):
        if callable(action):
            self._action = action
            raise Exception("callable action required") = target

    def execute(self, *args):

class CommandClient(object):
    """Generic command client class"""

    def __init__(self, subject):
        self.subject = subject
        self._commands = {}

    def reset_subject(self):

    def add_command(self, command_name, action):
        :param command_name: the name of the command
        :type command_name: string
        :param action: a method of 'subject'
        :type action: string
        command_name = command_name.strip().upper()
        action = getattr(self.subject, action, None)
        if action:
            self._commands[command_name] = Command(action, self.subject)
            raise Exception("invalid action %s" % action)

    def execute(self, cmd, *args):
        :param cmd: command name
        :type cmd: string
        :param args: possible arguments for command
        :type args: optional input parameters for command
        cmd = cmd.strip().upper()
        command = self._commands.get(cmd)
        if command is None:
            print 'Unknown command ', cmd

    def query(self, attr):
        :param attr: name of attribute for 'subject'
        :type attr: string
        return getattr(self.subject, attr, "Undefined")

class Light(object):
    """An example command receiver class"""

    ON = "ON"
    OFF = "OFF"

    def __init__(self):
        self.state = Light.OFF

    def turn_on(self):
        print "Switching the lights on"
        self.state = Light.ON

    def turn_off(self):
        print "Switching the lights off"
        self.state = Light.OFF

class Car(object):
    """Another example command receiver class"""

    PETROL_IN_100 = 6.5

    def __init__(self):
        self.engine_running = False
        self.speed = 0.0
        self.fuel = 0.0

    def start(self):
        if self.fuel > 0.0:
            print "The car engine is starting..."
            self.engine_running = True
            print "The car tank is empty"

    def drive(self, distance):
        " drive distance kilometres"
        if self.engine_running:
            fuel_required = distance*self.PETROL_IN_100/100.0
            if self.fuel < fuel_required:
                print "The car needs fuel"
                print "  travelled %s kms" % distance
                self.fuel -= fuel_required
                print "  %s litres of petrol left" % self.fuel
            print "Car engine hasn't been started..."

    def fill_up_with_petrol(self, amount):
        self.fuel += amount

if __name__ == "__main__":

    print "========= Lights ==========="
    light_switch = CommandClient(Light())
    light_switch.add_command("ON", "turn_on")
    light_switch.add_command("OFF", "turn_off")

    print "The lamp is", light_switch.query("state")
    print "The lamp is", light_switch.query("state")
    print "Invalid Command for lights"
    print "Lamp is", light_switch.query("state")

    print "====== Fine ride ========"
    car_ride = CommandClient(Car())
    car_ride.add_command("fill", "fill_up_with_petrol")
    car_ride.add_command("Start", "start")
    car_ride.add_command("DRIVE", "drive")

    car_ride.execute("FILL", 15)
    print "fuel: ", car_ride.query("fuel")
    car_ride.execute("DRIVE", 34)

    print "==== Fool's ride  ======="

    print "fuel: ", car_ride.query("fuel")
    car_ride.execute("DRIVE", 77)
    print "fuel: ", car_ride.query("fuel")
    car_ride.execute("FILL", 15)
    car_ride.execute("DRIVE", 18843)
    print "fuel: ", car_ride.query("fuel")            

public by mprisznyak  3273  0  6  2

Tell it in code

Descriptive code, please, instead of descriptions in comments
# Not so good
class BadWidget(object):
  A Widget which draws itself
  def __init__(self, **params):
    self.params = params
    self.flags = 0b0000

  def set_flags(self, new_value):
    self.flags |= new_value

  def draw(self):
    if self.flags & 0b1000:  # Am I visible?
      print ("You can see a real BadWidget!")

# Better
class GoodWidget(BadWidget):

  def is_visible(self):
    return self.flags & 0b1000

  def draw(self):
    if self.is_visible:
      print ("You can see a real GoodWidget!")


public by mprisznyak  2682  1  6  2

Do something until you find a specific value in a sequence

The Bad, Ugly Villain and the Good, Handsome Hero
# test.txt contains this:
# 1
# 344
# ff
# and you want to count how many lines there are before "END"

# the ugly way
with open("test.txt") as f:
    counter = 0
    while True:
        line = f.readline()
        if line == 'END':
        counter += 1
print counter, "lines before END"

# the cool way                   
with open("test.txt") as f:
    counter = 0
    for line in iter(f.readline, 'END'):
        counter += 1
print counter, "lines before END"