Skip to content

Commit

Permalink
Make calling AbstractModule.__init__ without named arguments throw an…
Browse files Browse the repository at this point in the history
… exception.

PiperOrigin-RevId: 157694146
  • Loading branch information
Deepmind authored and adria-p committed Jun 12, 2017
1 parent 03ada1f commit 601c4f3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
9 changes: 8 additions & 1 deletion sonnet/python/modules/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ class AbstractModule(object):
sharing will not work.
"""

def __init__(self, name=None):
def __init__(self, _sentinel=None, name=None): # pylint: disable=invalid-name
"""Performs the initialisation necessary for all AbstractModule instances.
Every subclass of AbstractModule must begin their constructor with a call to
Expand All @@ -123,11 +123,18 @@ def __init__(self, name=None):
variable scope. Alternatively, instantiate sub-modules in `_build`.
Args:
_sentinel: Variable that only carries a non-None value if `__init__` was
called without named parameters. If this is the case, a deprecation
warning is issued in form of a `ValueError`.
name: Name of this module. Used to construct the Templated build function.
Raises:
ValueError: If name is not specified.
ValueError: If `__init__` was called without named arguments.
"""
if _sentinel is not None:
raise ValueError("Calling AbstractModule.__init__ without named "
"arguments is deprecated.")

if name is None or not isinstance(name, six.string_types):
raise ValueError("Name must be a string.")
Expand Down
13 changes: 12 additions & 1 deletion sonnet/python/modules/base_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
from __future__ import print_function

from functools import partial

import numpy as np
import six
from sonnet.python.modules import base
Expand Down Expand Up @@ -56,6 +55,13 @@ def _build(self, inputs):
return tf.identity(inputs)


class NoInitIdentityModule(base.AbstractModule):
"""Sonnet module that doesn't call `base.AbstractModule.__init__`."""

def _build(self, inputs):
return tf.identity(inputs)


class AbstractModuleTest(tf.test.TestCase):

def testInitializerKeys(self):
Expand Down Expand Up @@ -136,6 +142,11 @@ def testSubgraphsRecording(self):
self.assertIs(subgraphs[1].outputs, blah_outputs)
self.assertIs(subgraphs[2].outputs, baz_outputs)

def testInitNoNamedArgs(self):
"""Tests if calling __init__ without named args raises a ValueError."""
with self.assertRaises(ValueError):
NoInitIdentityModule("foobar")


def _make_model_with_params(inputs, output_size):
weight_shape = [inputs.get_shape().as_list()[-1], output_size]
Expand Down

0 comments on commit 601c4f3

Please sign in to comment.