Jump to content

  • Log In with Google      Sign In   
  • Create Account

Redefining a Function


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
5 replies to this topic

#1 samgj   Members   -  Reputation: 398

Like
0Likes
Like

Posted 16 July 2013 - 04:20 PM

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

MLNM-ONE: open source video game engine

Unincorporated Media's Website: my company's website


Sponsor:

#2 SiCrane   Moderators   -  Reputation: 9598

Like
0Likes
Like

Posted 16 July 2013 - 04:47 PM

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.

#3 LorenzoGatti   Crossbones+   -  Reputation: 2705

Like
0Likes
Like

Posted 17 July 2013 - 01:36 AM

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.
Produci, consuma, crepa

#4 King Mir   Members   -  Reputation: 2000

Like
0Likes
Like

Posted 17 July 2013 - 03:09 PM

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.



#5 Goran Milovanovic   Members   -  Reputation: 1104

Like
0Likes
Like

Posted 20 July 2013 - 11:45 PM

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


+---------------------------------------------------------------------+

| Game Dev video tutorials  ->   http://www.youtube.com/goranmilovano |
+---------------------------------------------------------------------+

#6 thok   Members   -  Reputation: 693

Like
0Likes
Like

Posted 30 July 2013 - 02:03 AM

 

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.)






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS