need hint for refactoring

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • GHUM

    #1

    need hint for refactoring

    I have a bunch of function like:

    def p2neufrage(_):
    """ create new element"""
    anfrage,ergebni s=getanfrage()
    if ergebnis.get("s tatus","ok") == "ok":
    wert=anfrage["feld"]
    # do something
    # unique here


    ergebnis["innerHTML"]=..... something ....

    #
    return simplejson.dump s(ergebnis, skipkeys=False,
    ensure_ascii=Fa lse, check_circular= True, allow_nan=True)


    so, everywhere there is the same beginning:

    anfrage,ergebni s=getanfrage()

    I analyze some transmitted jason-document; check for errors

    then I take the values out of the request, process it and fill the
    slots of a result ("ergebnis") dictionary, which is returned.


    So the beginning and the end of the function is allways repeated. It
    would be great to factor it out ... i startet with that ...getanfrage()
    call.

    Is there anything more possible?

    Thanks for any hint

    Harald

  • Diez B. Roggisch

    #2
    Re: need hint for refactoring

    GHUM wrote:
    I have a bunch of function like:
    >
    def p2neufrage(_):
    """ create new element"""
    anfrage,ergebni s=getanfrage()
    if ergebnis.get("s tatus","ok") == "ok":
    wert=anfrage["feld"]
    # do something
    # unique here
    >
    >
    ergebnis["innerHTML"]=..... something ....
    >
    #
    return simplejson.dump s(ergebnis, skipkeys=False,
    ensure_ascii=Fa lse, check_circular= True, allow_nan=True)
    >
    >
    so, everywhere there is the same beginning:
    >
    anfrage,ergebni s=getanfrage()
    >
    I analyze some transmitted jason-document; check for errors
    >
    then I take the values out of the request, process it and fill the
    slots of a result ("ergebnis") dictionary, which is returned.
    >
    >
    So the beginning and the end of the function is allways repeated. It
    would be great to factor it out ... i startet with that ...getanfrage()
    call.
    >
    Is there anything more possible?
    Use a decorator, out of my head:

    def foo(f):
    def _w(*args, **kwargs):
    anfrage,ergebni s=getanfrage()
    new_args = (args[0],) + (anfrage, ergebnis) + args[1:]
    f(*new_args, **kwargs)
    return simplejson.dump s(ergebnis, skipkeys=False,
    ensure_ascii=Fa lse, check_circular= True, allow_nan=True)

    return _w

    Then do

    @foo
    def p2neufrage(_, anfrage, ergebnis):
    """ create new element"""
    if ergebnis.get("s tatus","ok") == "ok":
    wert=anfrage["feld"]
    # do something
    # unique here
    ergebnis["innerHTML"]=..... something ....


    Diez

    Comment

    Working...