1

I have this function:

def icaocode(code):
    c.execute("SELECT ICAO, LAT, LON FROM airports WHERE ICAO = ?", (code,))
    result = c.fetchone()
    if result is None:
        print("No airport found with ICAO code", code)
        sys.exit()
    else:
        print("Found", code)
        [...]

Lets say I call this function with

icaocode(x)

How do I get the function to overwrite x with the results?

Caesius
  • 267
  • 2
  • 6
  • 16

3 Answers3

4

In function def:

def icaocode(code):
    ...
    return code  # new value

When calling:

x = icaocode(x)

Btw if the argument is mutable (like a list), you can overwrite it without returning the new value. If it's immutable (like a string, integer), you can't.

E.g.

def f(some_list):
    some_list.append("something")

In this case

my_list = []
f(my_list)

my_list will be ["something"]

Andras Nemeth
  • 319
  • 3
  • 10
4

You can't overwrite the value of the parameter. That is, you can't change it to refer to another object. You can, however, change the object. There is an old thread on pass-by-value and pass-by-reference semantics in Python that you may find illuminating: https://stackoverflow.com/a/986145/399047

For example, you can append elements to a list that is passed in as a parameter. The following code:

def func(a_list):
    a_list.append("some value")

l = [1,2,3]
print l
func(l)
print l

would give:

[1,2,3]
[1,2,3,"some value"]

In contrast, a string, cannot be modified. The following code:

def func2(a_str):
    a_str += "suffix"

s = "test"
print s
func2(s)
print s

would give:

"test"
"test"

My recommendation, unless you have a good reason, is to avoid mutating your input parameters, and return the modified object instead. Side-effects can make for messy code.

If, at the end of all this you really want to modify your input parameter, one technique would be to wrap the code parameter inside another object. e.g.

def icaocode(code_list):
    input_code = code_list[0]
    [...]
    # do something to input_code, assign result to
    # output_code
    [...]
    code_list[0] = output_code

Then you would call with:

code_list = [code]
icaocode(code_list)

That said, this code is ugly to me, smells something awful, and I don't recommend it.

Community
  • 1
  • 1
seggy
  • 434
  • 2
  • 7
2

You can, but it is a horrible way to conduct business. Return the value instead, remember that you can return more than one value if you like. Here is however one way to return a value through a parameter. But don't use it.

>>> def a(b):
...     b[0] = 'hi'
....
>>> c = ['nono']
>>> a(c)
>>> print(c)
['hi']
Jonas Byström
  • 25,316
  • 23
  • 100
  • 147