Using builtin name as local variable but also as builtin [duplicate]

2024/10/9 21:19:50

I have the following function:

def x():print(min(0, 1))min = 7print(min)

On the face of it (naively), it should print 0, then 7. In fact it raises an error:

Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<stdin>", line 2, in x
UnboundLocalError: local variable 'min' referenced before assignment

How does defining min as a local variable in min = 7 prevent it from being used as the builtin before hand? Does Python build a list of local variables (something like __slots__ for a class) as it is compiling the function?

Answer

The compile phase for Python identifies all names that are assigned to within the scope of a function, and marks those names as locals (they're assigned an index in a local variable array in CPython, so using them doesn't involve dictionary lookups at all).

Being a local is all or nothing, for the entire scope of the method. You can't treat a variable as local for part of the method, and global/built-in for the rest. Per the language reference on naming and binding:

A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block.

Like most language standards, that's rather dry, but the important point is that defining a local variable within the block makes it local for the (implied) whole block, not from point of definition.

If you need to do something like this, you can make a local from the qualified name of the builtin initially, then change it later, e.g.:

import builtins  # On Python 2, __builtin__def x():min = builtins.minprint(min(0, 1))min = 7print(min)

Or you can use a cheesy hack based on compile-time default value caching for the same purpose:

def x(min=min): # Caches builtin function as a default value for local minprint(min(0, 1))min = 7print(min)

If you're on Python 3, you'd want to do def x(*, min=min): to make it a keyword only argument, so it can't be overridden by the caller if they accidentally pass too many arguments positionally.

https://en.xdnf.cn/q/118535.html

Related Q&A

How to print the results of a SQLite query in python?

Im trying to print the results of this SQLite query to check whether it has stored the data within the database. At the moment it just prints None. Is there a way to open the database in a program like…

python sort strings with leading numbers alphabetically

I have a list of filenames, each of them beginning with a leading number:10_file 11_file 1_file 20_file 21_file 2_file ...I need to put it in this order:1_file 10_file 11_file 2_file 21_file 22_file ..…

Javascript is not recognizing a Flask variable

Im passing a set of variables into a Flask template, and I would like to first manipulate them with Javascript. The problem is that when I use the {{ var }} syntax, Javascript isnt recognizing it. The …

Float sum broken? [duplicate]

This question already has answers here:Is floating-point math broken?(36 answers)Closed 9 years ago.print(0.1 + 0.2 == 0.3)returnsFalseWhy?

SyntaxError: EOL while scanning string literal -Python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Formatting a return value from a serial device

I am reading a value from a device over serial, and the return value has the format: [Theoretical position in mm, Encoder position in mm], for example, b\r#-0.001504,-0.001516\n I would like to format …

if Else statement inside for loop is not working [duplicate]

This question already has answers here:Im getting an IndentationError (or a TabError). How do I fix it?(6 answers)Closed 6 months ago.am using following code to check certain conditionsfor myarg in my…

Sending data back and forth from android server to python client

I have posted this few days back but now i ran into another problem after solving that one. DESCRIPTION: working on an android app written in kotlin that behaves as a server side and Python program tha…

Loop to run 4 times to try run a SQL procedure, after 4 attempts then stop

I have attempted to write some code in python to do a loop 4 times. It will fail as spTest doesnt exist. So I want to try loop again (repeated 4 times total) if it still cant find it, I want to break o…

Loops in Python 3.4.3

I apologize ahead of time for my ignorance but I have trying to code something in python that requires a question to be asked to the user and the user responds. Dependent on that response, the program …