[Tutor] Assessing local variable outside function

Ben Finney ben+python at benfinney.id.au
Fri Oct 28 04:28:36 EDT 2016


Alan Gauld via Tutor <tutor at python.org> writes:

> On 28/10/16 02:38, nils wagenaar wrote:
> > Could i use a variable defined in a function in another function?

My answer would be: You can't because Python variables don't exist
outside their namespace.

You can make the object available in various ways, but not the variable.

> By returning it to the caller.

That's somewhat misleading. Returning the *object* would not grant
access to the local *variable*.

Nils, it's important to realise that a variable in Python is not
tractable: you can't hand them around, you can't access the name itself.
A Python variable exists only in its namespace, and can't move.

The variable is (at any given point) bound to an object; you can get
*other* variables bound to the same object by explicitly doing that.
Alan suggests one way.

Whether that meets your request to “use a variable defined in a function
in another function” will have to wait for you to check how the Python
data model actually works. Does that answer it, or do you need something
different?

-- 
 \     “Dare to be naïve.” —Richard Buckminster Fuller, personal motto |
  `\                                                                   |
_o__)                                                                  |
Ben Finney



More information about the Tutor mailing list