Skip to content

Commit

Permalink
Add utility to rename functions
Browse files Browse the repository at this point in the history
  • Loading branch information
stefanv committed Aug 27, 2015
1 parent 13b2170 commit 9fa408a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
21 changes: 21 additions & 0 deletions skimage/_shared/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from skimage._shared.utils import copy_func
import numpy.testing as npt


def test_copyfunc():
def foo(a):
return a

bar = copy_func(foo, name='bar')
other = copy_func(foo)

npt.assert_equal(bar.__name__, 'bar')
npt.assert_equal(other.__name__, 'foo')

other.__name__ = 'other'

npt.assert_equal(foo.__name__, 'foo')


if __name__ == "__main__":
npt.run_module_suite()
17 changes: 17 additions & 0 deletions skimage/_shared/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import functools
import sys
import numpy as np
import types

import six

Expand Down Expand Up @@ -174,3 +175,19 @@ def _mode_deprecations(mode):
"removed in a future release."))
mode = 'edge'
return mode


def copy_func(f, name=None):
"""Create a copy of a function.
Parameters
----------
f : function
Function to copy.
name : str, optional
Name of new function.
"""
return types.FunctionType(six.get_function_code(f),
six.get_function_globals(f), name or f.__name__,
six.get_function_defaults(f), six.get_function_closure(f))

0 comments on commit 9fa408a

Please sign in to comment.