2

I would like to use function of same name from different packages dependent on a function flag:

import chainer.functions as F
def random_q_z(input, test = False):
    if test:
        F = np
        # ...
    else:
        # ...
        pass

    return F.sum(input)

However the interpreter protests:

UnboundLocalError: local variable 'F' referenced before assignment

How to please it and do conditional referencing of packages?


I see that this question relates to other questions on variable scopes, but here the question is about how to handle different scopes. And the answer I got is valuable for this particular question.

Dima Lituiev
  • 12,544
  • 10
  • 41
  • 58
  • I don't get what `F = np` is supposed to do but that line is the problem. If you have a read-only variable in a function (it just uses the value from a higher scope), you can do this. However, _reassigning_ it in the function body makes it a local, and since it's called regardless but only defined (locally) in the `if` branch, you get this error. – Two-Bit Alchemist Nov 20 '15 at 20:17

1 Answers1

2

Make F a default parameter:

import chainer.functions as F

def random_q_z(input, test=False, F=F):
    if test:
        F = np

    return F.sum(input)

If you don't provide F as an argument when calling random_q_z, chainer.functions is used. You can also give random_q_z a different function for F.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161