0

I am having an issue where I want to bring a variable into a function by name.

I have tried this so far:

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

>>>print func()
25
>>>x = 4
>>>print func()
25

However if I try to edit that input variable after I input the code the number the function detects the old input so it would still print 25 as oppose to the new input squared.

Is there a cleaner way to pull a variable into a function that actually works?

deadfire19
  • 329
  • 2
  • 16

5 Answers5

0

Default functions values are calculated during function creation time, so even if you change the value of x it is not going to be changed in the function.

From docs:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call.

Read: Using mutable objects as default value can lead to unexpected results.

If you want to access a global value then simply do:

def func():
    return x**2

Or better pass it explicitly:

def func(y):
   return y**2

Another reason why not to use global variables inside function:

>>> x = 10
>>> def func():
...     print x
...     x = 5
...     
>>> func()
Traceback (most recent call last):
    func()
  File "<ipython-input-5-ab38e6cadf6b>", line 2, in func
    print x
UnboundLocalError: local variable 'x' referenced before assignment

Using classes:

class A:
    x = 5
    @staticmethod
    def func():
        return A.x**2
...     
>>> A.func()
25
>>> A.x = 10
>>> A.func()
100
Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

Just reference the global variable directly, instead of using it as the default value of an argument.

def func():
    return x ** 2
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

The default value of y is set during function definition, not when running it. So default value for y is set to value of x on def line.

This should work:

def func(y=None):
    if y is None:
        y = x
    return y ** 2
warvariuc
  • 57,116
  • 41
  • 173
  • 227
0

Generally in python Keyword Arguments are always assigned a value and you cant change that assigned value . So in your code

x=5
def func(y = x):
    return y ** 2
print func()
x=4
print func()

For the keyword argument y the value of x i.e 5 is assigned and we cant change that value. So even if you change the value of x you will get the same output as 25

To solve this the function might directly access the global variable and return the value like the below code

x=5
def func():
   return x ** 2
print func()
x=4
print func()
Vineeth Guna
  • 388
  • 4
  • 10
0

This is the correct way to do this

x=5
def foo():
    global x
    return x**2

Or you can simply do it like this

x=5
def foo():
    return x**2

In this case the same global variable is referenced if it exists.

Sudhanshu Mishra
  • 2,024
  • 1
  • 22
  • 40