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?

pulkitag
  • 605
  • 6
  • 10
  • 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()` – juanpa.arrivillaga Feb 10 '17 at 00:23

1 Answers1

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
Community
  • 1
  • 1
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172