[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Can global variable be passed into Python function?

On Sat, 22 Feb 2014 18:29:02 +1100, Chris Angelico wrote:

> On Sat, Feb 22, 2014 at 6:18 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> Now I daresay that under the hood, Pascal is passing the address of foo
>> (or bar) to the procedure plus, but inside plus you don't see that
>> address as the value of b. You see the value of foo (or bar).
>> C does not do that -- you have to manually manage the pointers
>> yourself, while Pascal does it for you. And Python also has nothing
>> like that.
> Yep. I should have clarified that I wasn't talking about Pascal; I'm not
> fluent in the language (last time I did anything at all with Pascal was
> probably about ten years ago, and not much then). In C, it strictly does
> what I said: & takes the address of something, * dereferences an
> address. There's no way to "pass a variable" - you have to pass the
> address, and that has consequences if, for instance, you *return* an
> address and the variable ceases to exist. (Does Pascal have an
> equivalent of that?)

Yes, Pascal has pointers as a first-class data type. Syntax is similar to 
C, ^x is a pointer to x, p^ dereferences the pointer p.

> And Python has no such concept, anywhere. But anything that you can
> achieve in C using pointers, you can probably achieve in Python using
> more complex objects.

Not even that complex. Although Python doesn't do pointers, the model of 
the language is such that you don't need to. Where in C or Pascal you 
would pass a pointer to a record, in Python you just pass the record, 
safe in the knowledge that the entire record won't be copied.

There are a few idioms which don't work as neatly in Python as in Pascal, 
such as output parameter, but you don't need them. Just return a tuple. 
If you insist on an output parameter, do it like this:

def func(inarg, outarg):
    if inarg % 2:
        outarg[0] == "even"
        outarg[0] == "odd"
    return inarg + 1

out = [None]
x = 42

result = func(x, out)