How to dynamic insert more conditional statements into a function

S

Shane

Hi I am a newbie for Python

Here is a question, say I have a list L,

function foo is:

def foo(L):
if L[0] > 0: return True

if later I want another function goo which returns "True" when L[0]
and L[1] are both > 0, i.e.,

def goo(L):
if L[0] > 0 and L[1] > 0: return True

Can anybody tell me how can I write the function "goo" based upon the
function "foo"? Thanks!
I know if it is implementable, I should use "decorator". But I just
cannot figure out how.
 
E

Emile van Sebille

On 3/9/2010 1:48 PM Shane said...
Hi I am a newbie for Python

Here is a question, say I have a list L,

function foo is:

def foo(L):
if L[0]> 0: return True

if later I want another function goo which returns "True" when L[0]
and L[1] are both> 0, i.e.,

def goo(L):
if L[0]> 0 and L[1]> 0: return True


Here's one way...

def foo(L,deep=0):
return L[0] and not deep or foo(L[1:],deep-1)

Subject to clean up.

Emile
 
G

Gabriel Genellina

Hi I am a newbie for Python

Here is a question, say I have a list L,

function foo is:

def foo(L):
if L[0] > 0: return True

if later I want another function goo which returns "True" when L[0]
and L[1] are both > 0, i.e.,

def goo(L):
if L[0] > 0 and L[1] > 0: return True

Can anybody tell me how can I write the function "goo" based upon the
function "foo"? Thanks!
I know if it is implementable, I should use "decorator". But I just
cannot figure out how.

To implement goo based on foo:

def goo(L):
if foo(L) and L[1]>0: return True

I don't see how to use a decorator here - maybe your example became too
simple to be useful. A more realistic use case?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top