0

Consider the code in the file my_module.py:

class A(object):
  def __init__(self, x=er()):
    self.x = x

Now, when I import this module

import my_module

I get an error,

name 'er is not defined

While I understand that my_module does not have er defined, but I am never creating an instance of class A. Therefore it is puzzling that python tries to execute the __init__ callback when simply importing the module. Although, the __init__ call is not fully executed as explained by the example below:

class A(object):
  def __init__(self, x=5):
    self.x = x
    print ('I am here')

Now, when I import the module - nothing is printed and this is expected behavior.

I am puzzled why is function er called in the first example when I donot instantiate an object of class A. Any pointers to the documentation that explains this?

1
  • Anyway, x isn't acting as a callback here, if that's what you mean. You can just have a parameter er, and in __init__ you can do self.x = er() Commented Feb 10, 2017 at 0:23

1 Answer 1

3

Because in Python, default argument values are evaluated at definition time. See, for example this question, or this notorious question.

This is documented here

The default values are evaluated at the point of function definition in the defining scope, so that

i = 5

def f(arg=i):
    print(arg)

i = 6

f() will print 5.

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

This will print

[1]
[1, 2]
[1, 2, 3]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.