Python numbers.Integral() Examples

The following are 30 code examples of numbers.Integral(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numbers , or try the search function .
Example #1
Source File: fractions.py    From jawfish with MIT License 7 votes vote down vote up
def from_decimal(cls, dec):
        """Converts a finite Decimal instance to a rational number, exactly."""
        from decimal import Decimal
        if isinstance(dec, numbers.Integral):
            dec = Decimal(int(dec))
        elif not isinstance(dec, Decimal):
            raise TypeError(
                "%s.from_decimal() only takes Decimals, not %r (%s)" %
                (cls.__name__, dec, type(dec).__name__))
        if dec.is_infinite():
            raise OverflowError(
                "Cannot convert %s to %s." % (dec, cls.__name__))
        if dec.is_nan():
            raise ValueError("Cannot convert %s to %s." % (dec, cls.__name__))
        sign, digits, exp = dec.as_tuple()
        digits = int(''.join(map(str, digits)))
        if sign:
            digits = -digits
        if exp >= 0:
            return cls(digits * 10 ** exp)
        else:
            return cls(digits, 10 ** -exp) 
Example #2
Source File: utils.py    From mars with Apache License 2.0 6 votes vote down vote up
def check_random_state(seed):
    """
    Turn seed into a mt.random.RandomState instance

    :param seed:
        If seed is None, return the RandomState singleton used by mt.random.
        If seed is an int, return a new RandomState instance seeded with seed.
        If seed is already a RandomState instance, return it.
        Otherwise raise ValueError.
    :return:
    """
    from . import random as mtrand
    from numpy import random as np_mtrand

    if seed is None or seed is mtrand or seed is np_mtrand:
        return mtrand._random_state
    if isinstance(seed, (Integral, np.integer)):
        return mtrand.RandomState(seed)
    if isinstance(seed, np.random.RandomState):
        return mtrand.RandomState.from_numpy(seed)
    if isinstance(seed, mtrand.RandomState):
        return seed
    raise ValueError('%r cannot be used to seed a mt.random.RandomState'
                     ' instance' % seed) 
Example #3
Source File: geometric.py    From differential-privacy-library with MIT License 6 votes vote down vote up
def set_sensitivity(self, sensitivity):
        """Sets the sensitivity of the mechanism.

        Parameters
        ----------
        sensitivity : int
            The sensitivity of the mechanism.  Must satisfy `sensitivity` > 0.

        Returns
        -------
        self : class

        """
        if not isinstance(sensitivity, Integral):
            raise TypeError("Sensitivity must be an integer")

        if sensitivity < 0:
            raise ValueError("Sensitivity must be non-negative")

        self._sensitivity = sensitivity
        self._scale = None
        return self 
Example #4
Source File: fractions.py    From jawfish with MIT License 6 votes vote down vote up
def from_float(cls, f):
        """Converts a finite float to a rational number, exactly.

        Beware that Fraction.from_float(0.3) != Fraction(3, 10).

        """
        if isinstance(f, numbers.Integral):
            return cls(f)
        elif not isinstance(f, float):
            raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
                            (cls.__name__, f, type(f).__name__))
        if math.isnan(f):
            raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
        if math.isinf(f):
            raise OverflowError("Cannot convert %r to %s." % (f, cls.__name__))
        return cls(*f.as_integer_ratio()) 
Example #5
Source File: __init__.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def isint(obj):
    """
    Deprecated. Tests whether an object is a Py3 ``int`` or either a Py2 ``int`` or
    ``long``.

    Instead of using this function, you can use:

        >>> from future.builtins import int
        >>> isinstance(obj, int)

    The following idiom is equivalent:

        >>> from numbers import Integral
        >>> isinstance(obj, Integral)
    """

    return isinstance(obj, numbers.Integral) 
Example #6
Source File: geometric.py    From differential-privacy-library with MIT License 6 votes vote down vote up
def set_bounds(self, lower, upper):
        """Sets the lower and upper bounds of the mechanism.

        For the truncated geometric mechanism, `lower` and `upper` must be integer-valued.  Must have
        `lower` <= `upper`.

        Parameters
        ----------
        lower : int
            The lower bound of the mechanism.

        upper : int
            The upper bound of the mechanism.

        Returns
        -------
        self : class

        """
        if not isinstance(lower, Integral) or not isinstance(upper, Integral):
            raise TypeError("Bounds must be integers")

        return super().set_bounds(lower, upper) 
Example #7
Source File: __init__.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def no(mytype, argnums=(1,)):
    """
    A shortcut for the disallow_types decorator that disallows only one type
    (in any position in argnums).

    Example use:

    >>> class newstr(object):
    ...     @no('bytes')
    ...     def __add__(self, other):
    ...          pass

    >>> newstr(u'1234') + b'1234'     #doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    TypeError: argument can't be bytes

    The object can also be passed directly, but passing the string helps
    to prevent circular import problems.
    """
    if isinstance(argnums, Integral):
        argnums = (argnums,)
    disallowed_types = [mytype] * len(argnums)
    return disallow_types(argnums, disallowed_types) 
Example #8
Source File: base.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def to_native(self, value, context=None):
        if isinstance(value, bool):
            value = int(value)
        if isinstance(value, self.native_type):
            return value
        try:
            native_value = self.native_type(value)
        except (TypeError, ValueError):
            pass
        else:
            if self.native_type is float: # Float conversion is strict enough.
                return native_value
            if not self.strict and native_value == value: # Match numeric types.
                return native_value
            if isinstance(value, (string_type, numbers.Integral)):
                return native_value

        raise ConversionError(self.messages['number_coerce']
                              .format(value, self.number_type.lower())) 
Example #9
Source File: __init__.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def isint(obj):
    """
    Deprecated. Tests whether an object is a Py3 ``int`` or either a Py2 ``int`` or
    ``long``.

    Instead of using this function, you can use:

        >>> from future.builtins import int
        >>> isinstance(obj, int)

    The following idiom is equivalent:

        >>> from numbers import Integral
        >>> isinstance(obj, Integral)
    """

    return isinstance(obj, numbers.Integral) 
Example #10
Source File: __init__.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def no(mytype, argnums=(1,)):
    """
    A shortcut for the disallow_types decorator that disallows only one type
    (in any position in argnums).

    Example use:

    >>> class newstr(object):
    ...     @no('bytes')
    ...     def __add__(self, other):
    ...          pass

    >>> newstr(u'1234') + b'1234'     #doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    TypeError: argument can't be bytes

    The object can also be passed directly, but passing the string helps
    to prevent circular import problems.
    """
    if isinstance(argnums, Integral):
        argnums = (argnums,)
    disallowed_types = [mytype] * len(argnums)
    return disallow_types(argnums, disallowed_types) 
Example #11
Source File: base.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def to_native(self, value, context=None):
        if isinstance(value, bool):
            value = int(value)
        if isinstance(value, self.native_type):
            return value
        try:
            native_value = self.native_type(value)
        except (TypeError, ValueError):
            pass
        else:
            if self.native_type is float: # Float conversion is strict enough.
                return native_value
            if not self.strict and native_value == value: # Match numeric types.
                return native_value
            if isinstance(value, (string_type, numbers.Integral)):
                return native_value

        raise ConversionError(self.messages['number_coerce']
                              .format(value, self.number_type.lower())) 
Example #12
Source File: __init__.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def isint(obj):
    """
    Deprecated. Tests whether an object is a Py3 ``int`` or either a Py2 ``int`` or
    ``long``.

    Instead of using this function, you can use:

        >>> from future.builtins import int
        >>> isinstance(obj, int)

    The following idiom is equivalent:

        >>> from numbers import Integral
        >>> isinstance(obj, Integral)
    """

    return isinstance(obj, numbers.Integral) 
Example #13
Source File: __init__.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def no(mytype, argnums=(1,)):
    """
    A shortcut for the disallow_types decorator that disallows only one type
    (in any position in argnums).

    Example use:

    >>> class newstr(object):
    ...     @no('bytes')
    ...     def __add__(self, other):
    ...          pass

    >>> newstr(u'1234') + b'1234'     #doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    TypeError: argument can't be bytes

    The object can also be passed directly, but passing the string helps
    to prevent circular import problems.
    """
    if isinstance(argnums, Integral):
        argnums = (argnums,)
    disallowed_types = [mytype] * len(argnums)
    return disallow_types(argnums, disallowed_types) 
Example #14
Source File: options.py    From tornado-zh with MIT License 6 votes vote down vote up
def parse(self, value):
        _parse = {
            datetime.datetime: self._parse_datetime,
            datetime.timedelta: self._parse_timedelta,
            bool: self._parse_bool,
            basestring_type: self._parse_string,
        }.get(self.type, self.type)
        if self.multiple:
            self._value = []
            for part in value.split(","):
                if issubclass(self.type, numbers.Integral):
                    # allow ranges of the form X:Y (inclusive at both ends)
                    lo, _, hi = part.partition(":")
                    lo = _parse(lo)
                    hi = _parse(hi) if hi else lo
                    self._value.extend(range(lo, hi + 1))
                else:
                    self._value.append(_parse(part))
        else:
            self._value = _parse(value)
        if self.callback is not None:
            self.callback(self._value)
        return self.value() 
Example #15
Source File: utils.py    From pdfplumber with MIT License 6 votes vote down vote up
def _decimalize(v, q = None):
    # If already a decimal, just return itself
    if type(v) == Decimal:
        return v

    # If tuple/list passed, bulk-convert
    elif isinstance(v, (tuple, list)):
        return type(v)(decimalize(x, q) for x in v)

    # Convert int-like
    elif isinstance(v, numbers.Integral):
        return Decimal(int(v))

    # Convert float-like
    elif isinstance(v, numbers.Real):
        if q != None:
            return Decimal(repr(v)).quantize(Decimal(repr(q)),
                rounding=ROUND_HALF_UP)
        else:
            return Decimal(repr(v))
    else:
        raise ValueError("Cannot convert {0} to Decimal.".format(v)) 
Example #16
Source File: array.py    From recruit with Apache License 2.0 6 votes vote down vote up
def __setitem__(self, key, value):
        if isinstance(key, numbers.Integral):
            self.data[key] = value
        else:
            if not isinstance(value, (type(self),
                                      compat.Sequence)):
                # broadcast value
                value = itertools.cycle([value])

            if isinstance(key, np.ndarray) and key.dtype == 'bool':
                # masking
                for i, (k, v) in enumerate(zip(key, value)):
                    if k:
                        assert isinstance(v, self.dtype.type)
                        self.data[i] = v
            else:
                for k, v in zip(key, value):
                    assert isinstance(v, self.dtype.type)
                    self.data[k] = v 
Example #17
Source File: griddedfield.py    From typhon with MIT License 6 votes vote down vote up
def __init__(self, dimension=None, grids=None, data=None, gridnames=None,
                 dataname=None, name=None):
        """Create a GriddedField object.

        Parameters:
            dimension (int): Dimension of the GriddedField.
            grids (list, tuple, np.ndarray): grids.
            data (np.ndarray): data values.
            gridnames (List[str]): clear names for all grids.
            dataname (str): name of the data array.
            name (str): name of the GriddedField.

        """
        if not isinstance(dimension, numbers.Integral) or dimension < 1:
            raise ValueError('dimension must be a scalar greater 0')
        self._dimension = dimension
        self.grids = copy.deepcopy(grids)
        self.data = copy.copy(data)
        self.gridnames = copy.copy(gridnames)
        self.dataname = dataname
        self.name = name 
Example #18
Source File: griddedfield.py    From typhon with MIT License 6 votes vote down vote up
def scale(self, key, factor, dtype=float):
        """Scale data stored in field with given fieldname.

        Notes:
              This method only works, if the first grid
              is an :arts:`ArrayOfString`.

        Parameters:
              key (str): Name of the field to scale.
              factor (float or ndarray): Scale factor.
              dtype (type): Data type used for typecasting. If the original
                dtype of ``GriddedField.data`` is ``int``, the data array
                gets typecasted to prevent messy behaviour when assigning
                scaled values.
        """
        if issubclass(self.data.dtype.type, numbers.Integral):
            # Typecast integer data arrays to prevent unwanted typecast when
            # assigning scaled (float) variables back to the (integer) ndarray.
            self.data = self.data.astype(dtype)

        self.set(key, self.get(key) * factor) 
Example #19
Source File: griddedfield.py    From typhon with MIT License 6 votes vote down vote up
def add(self, key, offset, dtype=float):
        """Add offset to data stored in field with given fieldname.

        Notes:
              This method only works, if the first grid
              is an :arts:`ArrayOfString`.

        Parameters:
              key (str): Name of the field to offset.
              offset (float or ndarray): Offset.
              dtype (type): Data type used for typecasting. If the original
                dtype of ``GriddedField.data`` is ``int``, the data array
                gets typecasted to prevent messy behaviour when assigning
                scaled values.
        """
        if issubclass(self.data.dtype.type, numbers.Integral):
            # Typecast integer data arrays to prevent unwanted typecast when
            # assigning scaled (float) variables back to the (integer) ndarray.
            self.data = self.data.astype(dtype)

        self.set(key, self.get(key) + offset) 
Example #20
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
def _convert_header_value(self, value):
        if isinstance(value, bytes):
            pass
        elif isinstance(value, unicode_type):
            value = value.encode('utf-8')
        elif isinstance(value, numbers.Integral):
            # return immediately since we know the converted value will be safe
            return str(value)
        elif isinstance(value, datetime.datetime):
            return httputil.format_timestamp(value)
        else:
            raise TypeError("Unsupported header value %r" % value)
        # If \n is allowed into the header, it is possible to inject
        # additional headers or split the request.
        if RequestHandler._INVALID_HEADER_CHAR_RE.search(value):
            raise ValueError("Unsafe header value %r", value)
        return value 
Example #21
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
def _convert_header_value(self, value):
        if isinstance(value, bytes):
            pass
        elif isinstance(value, unicode_type):
            value = value.encode('utf-8')
        elif isinstance(value, numbers.Integral):
            # return immediately since we know the converted value will be safe
            return str(value)
        elif isinstance(value, datetime.datetime):
            return httputil.format_timestamp(value)
        else:
            raise TypeError("Unsupported header value %r" % value)
        # If \n is allowed into the header, it is possible to inject
        # additional headers or split the request.
        if RequestHandler._INVALID_HEADER_CHAR_RE.search(value):
            raise ValueError("Unsafe header value %r", value)
        return value 
Example #22
Source File: getitem.py    From mars with Apache License 2.0 6 votes vote down vote up
def dataframe_getitem(df, item):
    columns = df.columns_value.to_pandas()

    if isinstance(item, (np.ndarray, pd.Series)) and item.dtype != np.bool_:
        item = item.tolist()

    if isinstance(item, slice):
        edge = item.start if item.start is not None else item.stop
        if isinstance(edge, Integral):
            return df.iloc[item]
        else:
            return df.loc[item]
    elif isinstance(item, list):
        for col_name in item:
            if col_name not in columns:
                raise KeyError('%s not in columns' % col_name)
        op = DataFrameIndex(col_names=item, output_types=[OutputType.dataframe])
    elif isinstance(item, _list_like_types) or hasattr(item, 'dtypes'):
        # NB: don't enforce the dtype of `item` to be `bool` since it may be unknown
        op = DataFrameIndex(mask=item, output_types=[OutputType.dataframe])
    else:
        if item not in columns:
            raise KeyError('%s not in columns' % item)
        op = DataFrameIndex(col_names=item)
    return op(df) 
Example #23
Source File: l10n.py    From EDMarketConnector with GNU General Public License v2.0 6 votes vote down vote up
def stringFromNumber(self, number, decimals=None):
        # Uses the current system locale, irrespective of language choice.
        # Unless `decimals` is specified, the number will be formatted with 5 decimal
        # places if the input is a float, or none if the input is an int.
        if decimals == 0 and not isinstance(number, numbers.Integral):
            number = int(round(number))
        if platform == 'darwin':
            if not decimals and isinstance(number, numbers.Integral):
                return self.int_formatter.stringFromNumber_(number)
            else:
                self.float_formatter.setMinimumFractionDigits_(decimals or 5)
                self.float_formatter.setMaximumFractionDigits_(decimals or 5)
                return self.float_formatter.stringFromNumber_(number)
        else:
            if not decimals and isinstance(number, numbers.Integral):
                return locale.format('%d', number, True)
            else:
                return locale.format('%.*f', (decimals or 5, number), True) 
Example #24
Source File: utils.py    From mars with Apache License 2.0 6 votes vote down vote up
def indexing_index_value(index_value, indexes, store_data=False):
    pd_index = index_value.to_pandas()
    if not index_value.has_value():
        new_index_value = parse_index(pd_index, indexes, store_data=store_data)
        new_index_value._index_value._min_val = index_value.min_val
        new_index_value._index_value._min_val_close = index_value.min_val_close
        new_index_value._index_value._max_val = index_value.max_val
        new_index_value._index_value._max_val_close = index_value.max_val_close
        return new_index_value
    else:
        if isinstance(indexes, Integral):
            return parse_index(pd_index[[indexes]], store_data=store_data)
        elif isinstance(indexes, Entity):
            if isinstance(pd_index, pd.RangeIndex):
                return parse_index(
                    pd.RangeIndex(-1), indexes, index_value, store_data=False)
            else:
                return parse_index(
                    type(pd_index)([]), indexes, index_value, store_data=False)
        if isinstance(indexes, tuple):
            return parse_index(pd_index[list(indexes)], store_data=store_data)
        else:
            return parse_index(pd_index[indexes], store_data=store_data) 
Example #25
Source File: dataset.py    From rankeval with Mozilla Public License 2.0 6 votes vote down vote up
def _check_random_state(seed):
        """
        Turn seed into a np.random.RandomState instance (took for sklearn)

        Parameters
        ----------
        seed : None | int | instance of RandomState
            If seed is None, return the RandomState singleton used by np.random.
            If seed is an int, return a new RandomState instance seeded with it.
            If seed is already a RandomState instance, return it.
            Otherwise raise ValueError.
        """
        if seed is None or seed is np.random:
            return np.random.mtrand._rand
        if isinstance(seed, (numbers.Integral, np.integer)):
            return np.random.RandomState(seed)
        if isinstance(seed, np.random.RandomState):
            return seed
        raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
                         ' instance' % seed) 
Example #26
Source File: html.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _get_skiprows(skiprows):
    """Get an iterator given an integer, slice or container.

    Parameters
    ----------
    skiprows : int, slice, container
        The iterator to use to skip rows; can also be a slice.

    Raises
    ------
    TypeError
        * If `skiprows` is not a slice, integer, or Container

    Returns
    -------
    it : iterable
        A proper iterator to use to skip rows of a DataFrame.
    """
    if isinstance(skiprows, slice):
        return lrange(skiprows.start or 0, skiprows.stop, skiprows.step or 1)
    elif isinstance(skiprows, numbers.Integral) or is_list_like(skiprows):
        return skiprows
    elif skiprows is None:
        return 0
    raise TypeError('%r is not a valid type for skipping rows' %
                    type(skiprows).__name__) 
Example #27
Source File: scattering.py    From typhon with MIT License 5 votes vote down vote up
def __getitem__(self, v):
        """Get subset of single-scattering-data

        Must np.take four elements (f, T, za, aa).
        Only implemented for randomly oriented particles.
        """

        if self.ptype != PARTICLE_TYPE_TOTALLY_RANDOM:
            raise RuntimeError("Slicing implemented only for"
                               "ptype = %d. Found ptype = %d" %
                               (PARTICLE_TYPE_TOTALLY_RANDOM, self.ptype))
        v2 = list(v)
        for i, el in enumerate(v):
            # to preserve the rank of the data, [n] -> [n:n+1]
            if isinstance(el, numbers.Integral):
                v2[i] = slice(v[i], v[i] + 1, 1)
        f, T, za, aa = v2
        # make a shallow copy (view of the same data)
        c = copy.copy(self)
        c.f_grid = c.f_grid[f]
        c.T_grid = c.T_grid[T]
        c.za_grid = c.za_grid[za]
        c.aa_grid = c.aa_grid[aa]
        c.ext_mat_data = c.ext_mat_data[f, T, :, :, :]
        c.pha_mat_data = c.pha_mat_data[f, T, za, aa, :, :, :]
        c.abs_vec_data = c.abs_vec_data[f, T, :, :, :]
        c.checksize()
        return c 
Example #28
Source File: np_conserved.py    From tenpy with GNU General Public License v3.0 5 votes vote down vote up
def get_leg_index(self, label):
        """translate a leg-index or leg-label to a leg-index.

        Parameters
        ----------
        label : int | string
            The leg-index directly or a label (string) set before.

        Returns
        -------
        leg_index : int
            The index of the label.

        See also
        --------
        get_leg_indices : calls get_leg_index for a list of labels.
        iset_leg_labels : set the labels of different legs.
        """
        if not isinstance(label, Integral):
            try:
                label = self._labels.index(label)
            except ValueError:  # not in List
                msg = "Label not found: {0!r}, current labels: {1!r}".format(label, self._labels)
                raise KeyError(msg) from None
        else:
            if label < 0:
                label += self.rank
            if label > self.rank or label < 0:
                raise ValueError("axis {0:d} out of rank {1:d}".format(label, self.rank))
        return label 
Example #29
Source File: regularizers.py    From tensornets with MIT License 5 votes vote down vote up
def l2_regularizer(scale, scope=None):
  """Returns a function that can be used to apply L2 regularization to weights.

  Small values of L2 can help prevent overfitting the training data.

  Args:
    scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer.
    scope: An optional scope name.

  Returns:
    A function with signature `l2(weights)` that applies L2 regularization.

  Raises:
    ValueError: If scale is negative or if scale is not a float.
  """
  if isinstance(scale, numbers.Integral):
    raise ValueError('scale cannot be an integer: %s' % (scale,))
  if isinstance(scale, numbers.Real):
    if scale < 0.:
      raise ValueError('Setting a scale less than 0 on a regularizer: %g.' %
                       scale)
    if scale == 0.:
      logging.info('Scale of 0 disables regularizer.')
      return lambda _: None

  def l2(weights):
    """Applies l2 regularization to weights."""
    with ops.name_scope(scope, 'l2_regularizer', [weights]) as name:
      my_scale = ops.convert_to_tensor(scale,
                                       dtype=weights.dtype.base_dtype,
                                       name='scale')
      return standard_ops.multiply(my_scale, nn.l2_loss(weights), name=name)

  return l2 
Example #30
Source File: regularizers.py    From tensornets with MIT License 5 votes vote down vote up
def l1_regularizer(scale, scope=None):
  """Returns a function that can be used to apply L1 regularization to weights.

  L1 regularization encourages sparsity.

  Args:
    scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer.
    scope: An optional scope name.

  Returns:
    A function with signature `l1(weights)` that apply L1 regularization.

  Raises:
    ValueError: If scale is negative or if scale is not a float.
  """
  if isinstance(scale, numbers.Integral):
    raise ValueError('scale cannot be an integer: %s' % scale)
  if isinstance(scale, numbers.Real):
    if scale < 0.:
      raise ValueError('Setting a scale less than 0 on a regularizer: %g' %
                       scale)
    if scale == 0.:
      logging.info('Scale of 0 disables regularizer.')
      return lambda _: None

  def l1(weights, name=None):
    """Applies L1 regularization to weights."""
    with ops.name_scope(scope, 'l1_regularizer', [weights]) as name:
      my_scale = ops.convert_to_tensor(scale,
                                       dtype=weights.dtype.base_dtype,
                                       name='scale')
      return standard_ops.multiply(
          my_scale,
          standard_ops.reduce_sum(standard_ops.abs(weights)),
          name=name)

  return l1