[TasPython] Διαλέξτε το στυλ σας

Dimitris Glezos glezos at indifex.com
Wed Sep 1 16:53:33 CEST 2010


Πώς θα υλοποιούσατε την self.cycle() στη δική σας κλάση;

(code not necessarily 100% correct)


LEVEL_VALUES = {
    0: 'Normal',
    1: 'High',
    2: 'Top',
}

from django.db import models
class Priority(models.Model):
    level = models.IntegerField()


### 1 -- "The One-liner Showoff"

def cycle(self):
    self.level = (self.level + 1) % max(LEVEL_VALUES.keys())


### 2 -- "The Readability Nazi"

def cycle(self):
    if self.level == max(LEVEL_VALUES.keys()):
        self.level = 0
    else:
        self.level++


### 3 "The Re-usability Nerd"

def increase(self):
    if self.level + 1 == max(LEVEL_VALUES.keys()):
        raise OverflowError('No higher priority')
    self.level++

def cycle_up(self):
    try:
        self.increase()
    except OverflowError:
        self.level = 0


### 4 "The Iterator Abuser"

class MyModel():
    c = itertools.cycle(LEVEL_VALUES.keys())
    level = model.Field(mpla, mpla, default=self.c.next())
    def cycle(self):
        while self.level != self.c.next() # search for current key
            pass
        self.level = self.c.next()


### 5 -- "The lamda freak"

cycle = lambda pos: (lambda x: 0, lambda x: x+1)[pos>max-1](pos)


### More?

-- 
Dimitris Glezos

Transifex: The Multilingual Publishing Revolution
http://www.transifex.net/ -- http://www.indifex.com/


More information about the TasPython mailing list