• Advertisement
Sign in to follow this  

Redefining a Function

This topic is 1636 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In Python after a function has already been declared can it be redefined without it being completely redefined. Could I for example create a function then add or remove a statement from it?

 

For example say I have this:

def func(x, y):
    y = 2 * x
    return y

Then could I do something like this:

func() = func() - return y

So then the function would be only:

    y = 2 * x

Share this post


Link to post
Share on other sites
Advertisement
The short answer is no. Once you create a python function it gets transformed into a compiled code object, and there is no simple way to modify the code object.
 
However, you can use decorators to wrap functions to add functionality. It's also possible to compile python source to an AST and modify the AST such as with the ast module. If feeling really ambitious, the byte code for a code object can be seen via the co_code member of a code object, and that byte code could be manually manipulated. Doing so would have no guarantees of portability between python versions (including minor point versions). You may want to investigate the Python language services modules for more information about your options for dealing with compiled functions.

Share this post


Link to post
Share on other sites
First of all, your example is wrong: the function should not receive y as a parameter, as "y=2*x" defines a local variable named y. If you want to alter a global variable called y, you need to put "global y" inside your function to override the interpreter assumption that names are local variables.
C:\windows\system32>python
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> y=5
>>> def double1(x):
...     print(y)
...     y=x*2
...     print(y)
...
>>> print(y)
5
>>> double1(25)
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in double1
UnboundLocalError: local variable 'y' referenced before assignment
>>> def double2(x):
...     y=x*2
...     print(y)
...
>>> double2(25)
50
>>> print(y)
5
>>> def double3(x):
...     global y
...     y=x*2
...     print(y)
...
>>> double3(13)
26
>>> print(y)
26
Functions and classes are perfectly well behaved objects that you can replace as a whole, like this:.
C:\windows\system32>python
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x):
...     return x+1
...
>>> def g(x):
...     return x+2
...
>>> print(f(1))
2
>>> print(g(1))
3
>>> f,g = g,f
>>> print(f(1))
3
>>> print(g(1))
2
>>> f=None
>>> print(f(1))
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'NoneType' object is not callable
However, classes and functions are for practical purposes global data, and altering them might be a bad idea: conflicts between call sites who want different variations of the function are likely. Consider more mainstream solutions like using different functions or using additional parameters to get different behaviour.

Share this post


Link to post
Share on other sites

Firstly, the example given is ridiculous, because there is no benefit for having a function that's the same as another, except for the fact that it doesn't return a value. You can just not use the result in the caller. The overhead for returning a value is negligible, if not 0.

 

Secondly, a more general way of making functions out of other functions, is to have the larger function call the more specific functions it needs. The the user can call either the larger function, or the more specific function, depending on what is needed. The decorator's that SiCrane mentioned is a form of this.

Share this post


Link to post
Share on other sites
code = \
"""
def func(x, y):
	y = 2 * x
	return y
"""

code = code.split('\n')
code.pop(); code.pop(0)

exec("\n".join(code))

func(3, 2) # 6

exec("\n".join(code[:2])) # Only first 2 lines, excluding return

func(3, 2) # None

But don't ever do this. biggrin.png

Share this post


Link to post
Share on other sites

 

In Python after a function has already been declared can it be redefined without it being completely redefined. Could I for example create a function then add or remove a statement from it?

 

For example say I have this:

def func(x, y):
    y = 2 * x
    return y

Then could I do something like this:

func() = func() - return y

So then the function would be only:

    y = 2 * x

I think an important question here is, _why_ do you want to do this? I agree with King Mir--the example is not very realistic.

 

So what are you trying to do? Are you just trying to achieve partial reuse of a function? (If that's the case, you're better off just breaking this function into 2 or more, so that you can compose the individual parts for use in other situations.)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement