Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I feel the version from the original comment is most Pythonic. The other version is close to an eval-function, which seems to be frowned up on in Python.


The second version is slower too. Here's what I use for e.g. a state machine, which follows "don't repeat yourself" a little better than the first example:

  # {state_name: state_action}
  states = {}
  
  state = ['start']
  
  def reg(func):
    states[func.__name__] = func
    return func
  
  # define and simultaneously register the states
  @reg
  def start():
    state[0] = 'second'
  
  @reg
  def second():
    state[0] = 'last'
  
  @reg
  def last():
    state[0] = None
  
  
  # run the state machine
  while state[0]:
    print state[0]
    states[state[0]]()


Is the second version slower because the string won't get intern-ed?


Yeah, and the string must be reinterpolated every time (possibly barring some of the more exotic python implementations).


Why are you using mutation?




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: