countries = [“India”, “USA”, “France”, “Germany”]if len(countries) < 5:
print ("Length of countries is " + len(countries))
country_size = len(countries)if country_size < 5:
print ("Length of countries is " + country_size)
if country_size := len(countries) < 5 :
print ("Length of countries is " + country_size)
powers = [get_count(), get_count()**2, get_count()**3]
def get_count():
"Fetches count of records from a database"
powers =[result:= get_count(), result**2, result**3]
def get_count():
"Fetches count of records from a database"
employees = []
for id in employee_ids:
employee = fetch_employee(id)
if employee:
employees.append(employee)
employees = [result for id in employee_ids if (result:= fetch_employee(id))]
chunk = file.read(256)
while chunk:
process(chunk)
chunk = file.read(256)
while chunk := file.read(256) :
process(chunk)
obj = re.match(info).group(1) if re.match(info) else None
obj = match.group(1) if match:= re.match(info) else None
a = 5 # 有效
a := 5 # 无效
empty_list = [] # 有效
empty_list := [] # 无效
a += 5 # 有效
a :+=5 # 无效
(lambda: a:= 5) # 无效
lambda: (a := 5) # 有效但无用
(var := lambda: 5) # 有效
句法变化问题:开发者们为 := 提议了多种替代方案,比如「表达式 -> NAME」、「NAME -> 表达式」、「{表达式} NAME」等等。少数人建议使用现有的关键字,其他人则使用了新的算子。
后向兼容问题:这个特性无法向后兼容,也无法运行在之前的 Python 版本上。
算子名称问题:人们建议不要使用「海象算子」这样的代号,而是使用「赋值算子」、「命名表达式算子」、「成为算子」等术语,以免人们不明白。