
On Thu, May 28, 2020 at 08:04:07PM +1000, Chris Angelico wrote:
On Thu, May 28, 2020 at 8:01 PM Steven D'Aprano <steve@pearwood.info> wrote:
On Wed, May 27, 2020 at 05:03:09AM +1000, Chris Angelico wrote:
def foo(): if False: x = 0 # what is x now?
There is no *value* in x, yet x has a state.
In Python code, no, it has no state, it's just an unbound name. That's literally a name that has nothing bound to it, hence no state.
Is the UnboundLocalError that you'd get on trying to access 'x' a CPython implementation detail or a language feature?
I think the existence of UnboundLocalError is a red herring. See my recent post in this thread discussing Micropython. What *isn't* a red herring is whether or not x is treated as a local variable. That is a language feature. But whether it raises NameError or UnboundLocalError is, I think, up to the implementation.
If it's a language feature, then the name 'x' must be in the state of "local variable without a value".
Oh ho, I see what you are doing now :-) I'm going to stick with my argument that Python variables have two states: bound or unbound. But you want to talk about the *meta-state* of what scope they are in: LEGB = Local, Enclosing (nonlocal), Global, Builtin There's at least one other case not captured in that acronym, Class scope. There may be other odd corner cases. In any case, if you want to distinguish between "unbound locals" and "unbound globals" and even "unbound builtins", then I acknowledge that these are genuine, and important, distinctions to make, with real semantic differences in Python. But I think that the scope of a variable is metadata (metastate), when it comes to the state of any variable (whether LEGB or C) it can be bound to a value or unbound and that's all. At this point I'm not sure what, if any, difference to the current discusion it will make whether we label a variable's scope metastate or state.
This is a valid situation. There is no value, but this is the state of the variable. It's not "no state" any more than zero is a non-number or NULL is a non-pointer.
Zero is definitely a number with a value. It's the additive identity. NULL being a pointer is, I think, a mere consequence of the impoverished type systems of languages like C :-) The idea of NULL is that it should be just pointer-ish enough to satisfy the compiler and allow you to assign it to pointer variables, but not pointer-ish enough to fool the compiler into allowing you to dereference it and crash the machine. -- Steven