python _ underscore variable

本文探讨了Python中单下划线变量的三种主要用法:作为交互式解释器中上一条执行语句的结果;用于国际化的翻译查找;以及作为丢弃变量的名称,用于表示函数结果的一部分被故意忽略。

What is the meaning of _ after for in this code?

if tbh.bag:
   n = 0
   for _ in tbh.bag.atom_set():
      n += 1
share improve this question
 
5 
10 
While this question is marked as a duplicate, it and it's answers are a much better discussion of the problem than the question it allegedly duplicates. –  Zags  Oct 17 '13 at 20:54
 
For your case, it would be cleaner to either len(tbh.bag.atom_set()) (if the returned value has a __len__ method) or sum(1 for _ in tbh.bag.atom_set()) –  Nick T  Apr 5 at 20:08

2 Answers

up vote 314 down vote accepted

_ has 3 main conventional uses in Python:

  1. To hold the result of the last executed statement in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit
  2. For translation lookup in i18n (imported from the corresponding C conventions, I believe), as in code like: raiseforms.ValidationError(_("Please enter a correct username"))
  3. As a general purpose "throwaway" variable name to indicate that part of a function result is being deliberately ignored, as in code like: label, has_label, _ = text.partition(':')

The latter two purposes can conflict, so it is necessary to avoid using _ as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __, as their throwaway variable for exactly this reason).

share improve this answer
 
9 
Could you explain how it works in a function call, for example: raise forms.ValidationError(_("Please enter a correct username")). I've seen this in Django code, and it's not clear what's going on. –  John C  May 19 '11 at 13:43
17 
That is usage 2 - by convention, _ is the name used for the function that does internationalisation and localisation string translation lookups. I'm pretty sure it is the C gettext library that established that convention. –  ncoghlan  May 19 '11 at 16:47 
13 
FWIW, I've personally started using __ (a double underscore) as my general purpose throwaway variable to avoid conflicting with either of the first two use cases. –  ncoghlan  Mar 20 '12 at 6:35
 
This use of a single _ as a variable name for a throwaway variable isn't mentioned in PEP 8. Do you know of an authoritative source that suggests using it for that purpose? –  martineau  Jun 23 '15 at 19:30
4 
Emergent community conventions don't tend to have authoritative sources - just observations of the practices that have appeared over time. FWIW, I'm one of the co-authors of more recent PEP 8 updates, and my answer is based on the 3 different ways I've seen _ used as a variable name since I started using Python professionally in 2002. –  ncoghlan  Jun 28 '15 at 3:54
 
Thanks for the answer. Anyway I do not understand the advantage of marking a variable as not used. On the contrary, since one of the goals of Python is to let you make readable code, IMHO the use of the underscore character as variable or function name is not a good idea. –  Marco Sulla  Feb 25 at 13:18 
1 
The convention is mainly for tuple unpacking: a, __, c = iterable tells the reader immediately that we're unpacking a 3-tuple, but only using the first and last values. If we instead write a, b, c = iterable, the reader (or an automated code linter) can reasonably expect all of ab, and c to be used later (and if they're not, it may be a sign of a bug somewhere). –  ncoghlan  Feb 29 at 7:42
 
Based on the comments, I've now added examples for usages 2 & 3 directly to the answer. –  ncoghlan  Feb 29 at 7:55

It's just a variable name, and it's conventional in python to use _ for throwaway variables. It just indicates that the loop variable isn't actually used.

share improve this answer
 
3 
you mean it doesn't represent the last returned value? –  alwbtc  May 5 '11 at 5:52
16 
@steve only in a python shell –  Gabi Purcaru  May 5 '11 at 5:55
 
similar to the use of _ in Prolog –  Matthias  Feb 23 at 9:19


This question already has an answer here:

Peter Norvig has an essay describing a program to solve sudoku puzzles, even the hardest ones, by combining deterministic logical operations and smart traversal of the possible solutions. The latter is done recursively; here's that function (source):

def search(values):
    "Using depth-first search and propagation, try all possible values."
    if values is False:
        return False ## Failed earlier
    if all( len( values[s]) == 1 for s in squares): 
        return values ## Solved!
    ## Chose the unfilled square s with the fewest possibilities
    _,s = min( (len( values[s]), s) 
                for s in squares 
                if len(values[s]) > 1
            )
    return some( search( assign( values.copy(), s, d)) 
                for d in values[s]
            )

(I've added some spaces, CRs, and tabs for the sake of my eyes; apologies to Dr. Norvig.)

Right below the comment there's a line starting with "_,s". That seems to be the unpacked tuple (len(values[s]),s) with the minimal value of s. Is Dr. Norvig using "_" as a variable name just to indicate it's a "don't care" result, or is something else going on? Are there times when "_" is recommended as a variable name? In interactive mode, "_" holds the answer of the previous operation; is there a similar function in non-interactive code?

Update

Thanks for the good answers. I guess The Answer goes to Alex Martelli for "value added"; he points out that the "_, vbl_of_interest" idiom is often a side effect of the DSU idiom, which itself has been made largely unnecessary.

share improve this question

marked as duplicate by poke python Nov 12 '14 at 20:48

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

 
 
Another very popular solution nowadays is to get rid of the _ and just put [1] after the method call to project out the wished results. –  Trilarion  May 20 '14 at 8:25

3 Answers

up vote 49 down vote accepted

Yep, _ is a traditional name for "don't care" (which unfortunately clashes with its use in I18N, but that's a separate issue;-). BTW, in today's Python, instead of:

_,s = min( (len( values[s]), s) 
            for s in squares 
            if len(values[s]) > 1
        )

you might code

s = min((s for s in squares if len(values[s])>1), 
        key=lambda s: len(values[s]))

(not sure what release of Python Peter was writing for, but the idiom he's using is an example of "decorate-sort-undecorate" [[DSU]] except with min instead of sort, and in today's Python the key=optional parameter is generally the best way to do DSU;-).

share improve this answer
 
 
Hi, Alex. I was wondering about that, but I hadn't put it into the right concept --- and might not have, without your comment. BTW, my sudoku solver I wrote 4 years ago did a lot of DSU-ing, so you are pointing out places where I ought to update the coding. (Not to mention that I'm still trying to understand how the thing works!!) Typically, my code sets up its own explicit stack, rather than going recursive. –  behindthefall  Nov 16 '09 at 0:58
 
@behindthefall, controlling your own stack is just fine, though recursion's simpler -- there are specific techniques for recursion removal (not really germane to this question, but, do ask another)!. The one major case where manual DSU is still needed in today's Python, in my experience, is priority queues (heapq's function don't accept key= -- neither do bisect's, but that's not quite as common a use case for me as priority queues;-). –  Alex Martelli  Nov 16 '09 at 1:33
 
I'm trying to put recursion IN so that I can remove it when I wish --- my head hasn't learned how to do stuff with recursion that it wouldn't rather do with a loop. There's a load of code in my sudoku solver that this "simple" recursive def makes all go away! Dr. Norvig chose to use string ops rather than set ops in his solver; ironically, I used string ops to solve a few tiling puzzles before I tackled sudoku, so I used lists 'n' sets for sudoku just for the experience. –  behindthefall  Nov 16 '09 at 1:44
 
@behindthefall, yes, starting with recursion is generally best (simplest). Not sure what to suggest to help "getting" recursion, maybe a language-agnostic question would elicit responses from other people more experienced than me in such "teaching" issues! –  Alex Martelli  Nov 16 '09 at 1:56
 
Will the compiler recognize that '_' is thrown away and not actually assigning it (saving performance)? –  Viktor Mellgren  Jul 3 '12 at 8:15

You are correct. In non-interactive mode _ has no special meaning. Indeed, Norvig just wants to convey that he doesn't care about the value of that variable.

Offtopic: That article by Norvig is very nice. A recommended read.

share improve this answer
 
1 
Ah, very useful. Of course, doctests run in "interactive" mode: and tromp all over _ when you're trying to use it for i18n... –  Auspex  Oct 7 '14 at 22:34

Your interpretation is correct. Outside of the special meaning in interactive mode _ is just used as a "don't care" variable name, especially in unpacking.

share improve this answer


This question already has an answer here:

Peter Norvig has an essay describing a program to solve sudoku puzzles, even the hardest ones, by combining deterministic logical operations and smart traversal of the possible solutions. The latter is done recursively; here's that function (source):

def search(values):
    "Using depth-first search and propagation, try all possible values."
    if values is False:
        return False ## Failed earlier
    if all( len( values[s]) == 1 for s in squares): 
        return values ## Solved!
    ## Chose the unfilled square s with the fewest possibilities
    _,s = min( (len( values[s]), s) 
                for s in squares 
                if len(values[s]) > 1
            )
    return some( search( assign( values.copy(), s, d)) 
                for d in values[s]
            )

(I've added some spaces, CRs, and tabs for the sake of my eyes; apologies to Dr. Norvig.)

Right below the comment there's a line starting with "_,s". That seems to be the unpacked tuple (len(values[s]),s) with the minimal value of s. Is Dr. Norvig using "_" as a variable name just to indicate it's a "don't care" result, or is something else going on? Are there times when "_" is recommended as a variable name? In interactive mode, "_" holds the answer of the previous operation; is there a similar function in non-interactive code?

Update

Thanks for the good answers. I guess The Answer goes to Alex Martelli for "value added"; he points out that the "_, vbl_of_interest" idiom is often a side effect of the DSU idiom, which itself has been made largely unnecessary.

share improve this question

marked as duplicate by poke python Nov 12 '14 at 20:48

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

 
   
Another very popular solution nowadays is to get rid of the _ and just put [1] after the method call to project out the wished results. –  Trilarion  May 20 '14 at 8:25

3 Answers

up vote 49 down vote accepted

Yep, _ is a traditional name for "don't care" (which unfortunately clashes with its use in I18N, but that's a separate issue;-). BTW, in today's Python, instead of:

_,s = min( (len( values[s]), s) 
            for s in squares 
            if len(values[s]) > 1
        )

you might code

s = min((s for s in squares if len(values[s])>1), 
        key=lambda s: len(values[s]))

(not sure what release of Python Peter was writing for, but the idiom he's using is an example of "decorate-sort-undecorate" [[DSU]] except with min instead of sort, and in today's Python the key=optional parameter is generally the best way to do DSU;-).

share improve this answer
 
   
Hi, Alex. I was wondering about that, but I hadn't put it into the right concept --- and might not have, without your comment. BTW, my sudoku solver I wrote 4 years ago did a lot of DSU-ing, so you are pointing out places where I ought to update the coding. (Not to mention that I'm still trying to understand how the thing works!!) Typically, my code sets up its own explicit stack, rather than going recursive. –  behindthefall  Nov 16 '09 at 0:58
   
@behindthefall, controlling your own stack is just fine, though recursion's simpler -- there are specific techniques for recursion removal (not really germane to this question, but, do ask another)!. The one major case where manual DSU is still needed in today's Python, in my experience, is priority queues (heapq's function don't accept key= -- neither do bisect's, but that's not quite as common a use case for me as priority queues;-). –  Alex Martelli  Nov 16 '09 at 1:33
   
I'm trying to put recursion IN so that I can remove it when I wish --- my head hasn't learned how to do stuff with recursion that it wouldn't rather do with a loop. There's a load of code in my sudoku solver that this "simple" recursive def makes all go away! Dr. Norvig chose to use string ops rather than set ops in his solver; ironically, I used string ops to solve a few tiling puzzles before I tackled sudoku, so I used lists 'n' sets for sudoku just for the experience. –  behindthefall  Nov 16 '09 at 1:44
   
@behindthefall, yes, starting with recursion is generally best (simplest). Not sure what to suggest to help "getting" recursion, maybe a language-agnostic question would elicit responses from other people more experienced than me in such "teaching" issues! –  Alex Martelli  Nov 16 '09 at 1:56
   
Will the compiler recognize that '_' is thrown away and not actually assigning it (saving performance)? –  Viktor Mellgren  Jul 3 '12 at 8:15

You are correct. In non-interactive mode _ has no special meaning. Indeed, Norvig just wants to convey that he doesn't care about the value of that variable.

Offtopic: That article by Norvig is very nice. A recommended read.

share improve this answer
 
1 
Ah, very useful. Of course, doctests run in "interactive" mode: and tromp all over _ when you're trying to use it for i18n... –  Auspex  Oct 7 '14 at 22:34

Your interpretation is correct. Outside of the special meaning in interactive mode _ is just used as a "don't care" variable name, especially in unpacking.

share improve this answer
这是一个基于AI视觉识别与3D引擎技术打造的沉浸式交互圣诞装置。 简单来说,它是一棵通过网页浏览器运行的数字智慧圣诞树,你可以用真实的肢体动作来操控它的形态,并将自己的回忆照片融入其中。 1. 核心技术组成 这个作品是由三个尖端技术模块组成的: Three.js 3D引擎:负责渲染整棵圣诞树、动态落雪、五彩挂灯和树顶星。它创建了一个具备光影和深度感的虚拟3D空间。 MediaPipe AI手势识别:调用电脑摄像头,实时识别手部的21个关键点。它能读懂你的手势,如握拳、张开或捏合。 GSAP动画系统:负责处理粒子散开与聚合时的平滑过渡,让成百上千个物体在运动时保持顺滑。 2. 它的主要作用与功能 交互式情感表达: 回忆挂载:你可以上传本地照片,这些照片会像装饰品一样挂在树上,或者像星云一样环绕在树周围。 魔法操控:握拳时粒子迅速聚拢,构成一棵挺拔的圣诞树;张开手掌时,树会瞬间炸裂成星光和雪花,照片随之起舞;捏合手指时视线会拉近,让你特写观察某一张选中的照片。 节日氛围装饰: 在白色背景下,这棵树呈现出一种现代艺术感。600片雪花在3D空间里缓缓飘落,提供视觉深度。树上的彩色粒子和白色星灯会周期性地呼吸闪烁,模拟真实灯串的效果。 3. 如何使用 启动:运行代码后,允许浏览器开启摄像头。 装扮:点击上传照片按钮,选择温馨合照。 互动:对着摄像头挥动手掌可以旋转圣诞树;五指张开让照片和树化作满天星辰;攥紧拳头让它们重新变回挺拔的树。 4. 适用场景 个人纪念:作为一个独特的数字相册,在节日陪伴自己。 浪漫惊喜:录制一段操作手势让照片绽放的视频发给朋友。 技术展示:作为WebGL与AI结合的案例,展示前端开发的潜力。
【顶级EI复现】计及连锁故障传播路径的电力系统 N-k 多阶段双层优化及故障场景筛选模型(Matlab代码实现)内容概要:本文提出了一种计及连锁故障传播路径的电力系统N-k多阶段双层优化及故障场景筛选模型,并提供了基于Matlab的代码实现。该模型旨在应对复杂电力系统中可能发生的N-k故障(即多个元件相继失效),通过构建双层优化框架,上层优化系统运行策略,下层模拟故障传播过程,从而实现对关键故障场景的有效识别与筛选。研究结合多阶段动态特性,充分考虑故障的时序演化与连锁反应机制,提升了电力系统安全性评估的准确性与实用性。此外,模型具备良好的通用性与可扩展性,适用于大规模电网的风险评估与预防控制。; 适合人群:电力系统、能源互联网及相关领域的高校研究生、科研人员以及从事电网安全分析、风险评估的工程技术人员。; 使用场景及目标:①用于电力系统连锁故障建模与风险评估;②支撑N-k故障场景的自动化筛选与关键脆弱环节识别;③为电网规划、调度运行及应急预案制定提供理论依据和技术工具;④服务于高水平学术论文复现与科研项目开发。; 阅读建议:建议读者结合Matlab代码深入理解模型构建细节,重点关注双层优化结构的设计逻辑、故障传播路径的建模方法以及场景削减技术的应用,建议在实际电网数据上进行测试与验证,以提升对模型性能与适用边界的认知。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值