Replace variable of a function while calling it in python? - python

Sorry for my bad english.
Is there any way to replace variable of a method from outside?
Suppose i have two files app.py and try.py.
In app -
def call():
c=5
return c
In try -
from app import *
c=1000
d=call()
print(d)
When i run try, here i want the output to be 1000 not 6. Is there any way to do this ?

I don't know any way to change c dynamically. Python compiles c = 5 into a LOAD_CONST op code as seen in the disassembly. And changing that op code would require, um, .... I don't know.
>>> from dis import dis
>>> def call():
... c=5
... return c
...
>>> dis(call)
2 0 LOAD_CONST 1 (5)
2 STORE_FAST 0 (c)
3 4 LOAD_FAST 0 (c)
6 RETURN_VALUE
You can monkey patch, though. Write your own implemenation of call and assign it dynamically at the start of your program.
import app
# from app, a reimplementation of call
def my_app_call_impl(c=1000):
return c
app.call = my_app_call_impl

add c argument to the function and use it like that
app file
def call(c):
return c
The second file
from app import *
c = 1000
d = call(c)
print(d)
if you want to c have a default value then app file should look like this
def call(c = 5):

You can define parameters for the call function:
app.py:
def call(c): # one parameter, c
return c
try.py
from app import *
c = 1000
d = call(c) # function called with c as an argument
print(d) # 1000
You can also use 5 as a default:
app.py
def call(c = 5):
return c
try.py
from app import *
d = call()
print(d) # 5
Functions in Python

*in app.py : *
def call(c=5):
return c
*in try.py : *
from app import *
d=call(1000)
print(d)

Related

Call a function of inside function in main file from module using python

import math as m
def f1():
a = 10
b = 20
c = a+b
print(c)
print(m.sqrt(4))
def num(a,b):
d = a*b
return d
How to call to num function in another pycharm module ?
You can't, the function num(a,b) is essentially a local variable inside f1(); it only exists when f1() is ran.
Just write num(a,b) not as a nested function and you can call it elsewhere (if you import it properly) and f1() still has access to it:
import math as m
def num(a,b):
d = a*b
return d
def f1():
a = 10
b = 20
c = a+b
d = num(a,b)

Python - how to return values from function in other script

I want to return a value in a script MAIN.py where the function is stated in another script? How do I do this?
In a function SUB.py I have defined:
def SUM_POWER(a,b):
c = a+b
d = a**b
return [c,d]
Now I want to get in a script MAIN.py:
c and d for a=3 and b=4. I tried in MAIN.py:
import SUB
c,d = SUM_POWER(3,4)
What do I do wrong? Preferably I would want to name the variables in MAIN.py different than c,d. So for example out1, out2. out1 has to correspond to c and out2 corresponds to d by the order in which the values are returned.
The problem is in function call, as well as that you are returning a list while trying to store it in a tuple.
Try this SUB.py -
def SUM_POWER(a,b):
c = a+b
d = a**b
return c,d
MAIN.py -
import SUB
c,d = SUB.SUM_POWER(3,4)

Using math in loaded module in Python 3

in my main python file I just load the math module and an own module (called funcs.py). Finally, I run a function from the just loaded module.
import math
from funcs import *
RetentionTime(1,2,3,4)
The funcs.py file looks like this:
def RetentionTime(a, b, c, d):
"calculation of retention time"
RT = (11.2 * a) / (b * c * math.degrees( math.atan( d / 100 ) ) )
return RT
This leads to the following Nameerror:
NameError: name 'math' is not defined
In the python shell I can use commands like math.atan(...) without a problem. What am I doing wrong?
Thanks.
# test.py
y = 5
def f(x):
print(x+y)
Here f will bind the object named y from the innermost scope, which in this case is the module scope of test.py. Had it been as follows,
y = 5
def g():
y = 10
def f(x):
print(x+y)
return f
Here the y bound in f will be object 10. In your case RetentionTime is compiled in its own module scope and has no access to the scope of the caller. Hence add import math to the same module as RetentionTime.

Python getting a variable to change as what it's assigned to changes [duplicate]

This question already has answers here:
How to create recalculating variables in Python
(8 answers)
Closed 9 years ago.
For example, if I say:
a = 50
b = 3 * a
a = 46
The value of b after this runs would still be 3 * 50 = 150. How would I assign b to equal 3 * a such that when a changes, the value of b also changes, without me having to restate b = 3 * a again?
EDIT: I would have searched this up but I really wasn't sure how to word it.
With lambda function
You can create a lambda function. But, it requires you to add empty parenthesis after each call of b.
>>> a = 50
>>> b = lambda: a * 3
>>> b
<function <lambda> at 0xffedb304>
>>> b()
150
>>> a = 45
>>> b()
135
EDIT: I have already respond at this kind of anwser here: How to create recalculating variables in Python
With a homemade class
Another way given on this same thread is to create an Expression class, and change the repr return.
Fair warning: this is a hack only suitable for experimentation and play in a Python interpreter environment. Do not feed untrusted input into this code.
class Expression(object):
def __init__(self, expression):
self.expression = expression
def __repr__(self):
return repr(eval(self.expression))
def __str__(self):
return str(eval(self.expression))
>>> a = 5
>>> b = Expression('a + 5')
>>> b
10
>>> a = 20
>>> b
25
Make b into a function:
def b():
return 3 * a
then use it by calling it, i.e. b()
What do you thing of this way ? :
class XB(object):
def __getattribute__(self, name):
try:
return 3 * a
except:
return None
x = XB()
print 'x.b ==',x.b
a = 50
print 'x.b ==',x.b
a = 46
print 'x.b ==',x.b
return
x.b == None
x.b == 150
x.b == 138

Python extracting body from function at runtime

Given a function in Python defined as follows:
a = 3
b = 4
c = 5
def add():
d = a+b+c
is it possible to get a code object or similar that gives me:
a = 3
b = 4
c = 5
d = a+b+c
The function object has a code object associated with it; you can exec that code object:
>>> a = 3
>>> b = 4
>>> c = 5
>>> def add():
... d = a+b+c
...
>>> exec add.func_code
This will not however set d in the local namespace, because it is compiled to create a local name only, using the STORE_FAST opcode. You'd have to transform this bytecode to use STORE_DEREF opcodes instead, requiring you to learn AST transformations.
If you did want to go down this route, then read Exploring Dynamic Scoping in Python, which teaches you the ins and outs of Python scoping and byte code.
You can use the global command, which
is the most simple way in my opinion
>>> a = 3
>>> b = 4
>>> c = 5
>>> def add():
global d
... d = a+b+c

Categories