Error404
Error404

Reputation: 35

Return function from nested function in Python

def method(x, y, z):
   def nested_method(a, b, c):
      if a + b + c < 7:
         for i in range(0, 7):
            if i == a + b +c
               return i
   nested_method(3, 4, 0)
   nested_method(3, 0, 1)
   nested_method(1, 2, 0)

returns in method: None, 4, 3

If nested method returns something i want the method to return it. When i only need one answer i firtsly check the more prioritiesed.

first priority: 3, 4 and 0

second priority: 3, 0 and 1

...

so it would return 4

Upvotes: 2

Views: 3750

Answers (3)

Jacques Gaudin
Jacques Gaudin

Reputation: 16988

If I understand correctly you're looking for something like this:

def method(a, b, c):
    def nested_method(d, e):
        if d == e:
            return True

    for args in ((a, b), (b, c), (b, c)):
        if res := nested_method(*args) is not None: 
            return res # or return args

Upvotes: 0

Chris
Chris

Reputation: 36611

Perhaps what you're looking for is:

def method(a, b, c):
   def nested_method(d, e):
      if d == e:
         return True
   if nested_method(a, b) is not None: return True
   if nested_method(a, c) is not None: return True
   if nested_method(b, c) is not None: return True

If you wish to know which pair match:

def method(a, b, c):
   def nested_method(d, e):
      if d == e:
         return True
   if nested_method(a, b) is not None: return ('a', 'b')
   if nested_method(a, c) is not None: return ('a', 'c')
   if nested_method(b, c) is not None: return ('b', 'c')

Given the effect return has upon control flow, this works, but you could also write the following, using a conditional expression rather than statement.

def method(a, b, c):
   def nested_method(d, e):
      if d == e:
         return True
   return ('a', 'b') if nested_method(a, b) else ('a', 'c') if nested_method(a, c) else ('b', 'c') if nested_method(b, c) else None

Upvotes: 1

Ignatius Reilly
Ignatius Reilly

Reputation: 1750

This would return the first comparison that returns True

def method(a, b, c):
   def nested_method(d, e):
      if d == e:
         return True
   if nested_method(a, b):
      return nested_method(a, b)
   if nested_method(a, c):
      return nested_method(a, c)
   if nested_method(b, c):
      return nested_method(b, c)

You may want to add a printing statement to know which one is the one working...

This one would work in case that the three values are the same:

def method2(a, b, c):
   def nested_method(d, e):
      if d == e:
         return True
   
   comparisons = {'ab': nested_method(a, b), 'ac': nested_method(a, c), 'bc': nested_method(b, c)}

   return [comparisons[comp] for comp in comparisons if comparisons[comp] == True]

Upvotes: 1

Related Questions