0

Is this code correct in python?

def foo(flag):
    if flag:
        def bar():
           # Somthing
    else:
        def bar():
           # Somthing else
    bar()

foo(True)
foo(False)

if not what is a recommended way to set behavior of some function (bar) under? condition?

OK The real code is following

# Building replaceFunc based of ignore_case and use_regexp flags
if not ignore_case:
   if not use_regexp:
      def replaceFunc(string, search, replace):
          return string.replace(search, replace)
   else:
      def replaceFunc(string, search, replace):
          pattern = re.compile(search)
          return pattern.sub(replace, string)
else:
   if not use_regexp:
       # There is no standard puthon function for replacing string by ignoring case
       def replaceFunc(string, search, replace):
          # implementation from http://stackoverflow.com/questions/919056/case-insensitive-replace
           return string
   else:
        def replaceFunc(string, search, replace):
            pattern = re.compile(search, re.IGNORECASE)
            return pattern.sub(replace, string
ArmanHunanyan
  • 905
  • 3
  • 11
  • 24

1 Answers1

1

Here's one reasonable way to achieve what you want:

def bar1():
    return 'b1'

def bar2():
    return 'b2'

def foo(flag):
    bar = bar2 if flag else bar1
    return bar()

print(foo(False))
print(foo(True))

One benefit of defining the functions bar1() and bar2() outside of foo() is that they can be unit tested.

FMc
  • 41,963
  • 13
  • 79
  • 132
  • OK Thanks. This will work. Is the way to avoid from unneccary indiced names. In my case they will be bar1 bar2 bar3 bar4. Doesn't looks nice. – ArmanHunanyan Feb 19 '17 at 12:21
  • @ArmanHunanyan Sure, you can name the functions any way you like. Give them meaningful names — not `bar1`, `bar2`, etc. – FMc Feb 19 '17 at 12:47