53

Often when the syntax of the language requires me to name a variable that is never used, I'll name it _.

In my mind, this reduces clutter and lets me focus on the meaningful variables in the code. I find it to be unobtrusive so that it produces an "out of sight, out of mind" effect.

A common example of where I do this is naming subqueries in SQL.

SELECT *
FROM
(
    SELECT *
    FROM TableA
    JOIN TableB
        ON TableA.ColumnB = TableB.ColumnB
    WHERE [ColumnA] > 10
) _ --This name is required, but never used here
ORDER BY ColumnC

Another example is a loop variable that isn't used.

array = [[] for _ in range(n)] # Defines a list of n empty lists in Python

I use this technique very sparingly, only when I feel that a descriptive name adds nothing to the code, and in some sense takes away from it by adding more names to remember. In some ways I view it as similar to the var keyword in C#, which I also use sparingly.

My coworkers disagree. They say that even having a single (alphabetic) character name is better than _.

Am I wrong? Is it bad practice to do this?

Jim G.
  • 8,006
  • 3
  • 35
  • 66
Kris Harper
  • 2,237
  • 2
  • 19
  • 21
  • 4
    I think variable names should follow information theory, ie the length is the log reciprocal probability of their use (common variables have short names). A single alphabetical letter seems like the wrong way to go. – dan_waterworth May 04 '12 at 14:12
  • 2
    @dan_waterworth The use of single or double characters as table aliases is a pretty common practice in SQL scripts. Since you typically have to write a lot of `[table].[column]` identifiers, it helps readability a lot to just use `[T].[column]`. It depends on the script of course. A little select like that is perfectly fine, but if a script was very large, I might use more descriptive names. – CodexArcanum May 04 '12 at 14:50
  • Very strongly related (duplicate?): http://programmers.stackexchange.com/questions/122740/whats-the-idiomatic-name-for-a-throwaway-variable – Izkata May 04 '12 at 17:53
  • 5
    I'd rather you used "dummy". This screams to me that they're there because the language requires a variable that has no semantic context outside these few lines. _ doesn't read well to a human. (one of the reasons I hate PERL -- I can't type it or read it) – Chris Cudmore May 04 '12 at 18:52
  • 1
    Side note: What you're naming there is a [derived table](http://www.xaprb.com/blog/2005/09/26/sql-subqueries-and-derived-tables/), not a subquery. – Nick Chammas May 04 '12 at 21:15
  • @NickChammas Thank you, I didn't know that. – Kris Harper May 04 '12 at 23:07
  • 2
    The var keyword in c# has not this meaning, it's just a normal variable declaration where type is inferred. – Francesco De Vittori May 05 '12 at 06:13
  • @FrancescoDeVittori I meant in instances where `var` is unnecessary but used to shorten a declaration. E.g., why write `Dictionary dict = new Dictionary()` when you could write `var dict = new Dictionary()`? Here `var` isn't required, but it's solely used to remove clutter from the code. And similar to using `_`, using `var` too often can produce difficult to read code. – Kris Harper May 05 '12 at 12:25
  • http://stackoverflow.com/a/5477153/125507 – endolith Dec 08 '13 at 23:25

15 Answers15

62

All names should be meaningful. If _ was a well known standard at your company or in the wider community, then it would be meaningful as a "name that does not matter". If it's not, I would say it's bad practice. Use a descriptive name for what you refer to, especially since the name might matter in the future.

Filip Dupanović
  • 1,215
  • 8
  • 13
Telastyn
  • 108,850
  • 29
  • 239
  • 365
  • 13
    +1. `dummy` would be good, `joined_ab` would be better. – Blrfl May 04 '12 at 13:10
  • @Blrfl: I would even go so far as to recommend `unusedvar` or something of that nature unless for some reason byte count is important. – Joel Etherton May 04 '12 at 13:37
  • 5
    +1, There is a convention where I work to use '_' for unused variables. I think it's a good convention, but I agree with this answer for the OP's case. Ideally codebases should look as if they were written by a single person. – dan_waterworth May 04 '12 at 14:06
  • 24
    "_" is a well-known standard with Python. – Neil G May 04 '12 at 15:01
  • 2
    If your company uses any Perl, on the other hand, using $_ could cause sometimes surprising behavior. – Plutor May 04 '12 at 15:52
  • 3
    In prolog, an underscore indicates that the variable will be anonymous and therefor unused. – Ivan May 04 '12 at 17:32
  • `_` is a standard in Python as @NeilG says, but PyLint will complain about unused variables--rightfully so, because you can avoid them in all cases. – Filip Dupanović May 04 '12 at 19:26
  • 3
    @FilipDupanović Not in all cases (`z = [(a, b) for a, b, _ in foo()]`), but that's _why_ Python has `_` - it's for unused variables, and PyLint _doesn't_ complain about it. – Izkata May 04 '12 at 21:36
  • @Izkata I stand corrected ^^ – Filip Dupanović May 05 '12 at 00:27
  • 1
    @Niel: Where is this standard for Python defined? – martineau Jun 23 '15 at 19:37
  • 1
    I would say that a single `_` for unused variables is a well known standard across the entire industry. It's built-in in Haskell and in many functional languages like F#. It's de-facto standard in Lua, for example static analysis tools will ignore unused variables if named `_`. It's also very common in Python. – Joan Charmant Aug 27 '16 at 07:38
  • @joancharmant - having worked in the industry for almost 20 years now, I've known 2 other programmers who knew any of those languages. – Telastyn Aug 27 '16 at 13:13
  • 1
    Coming from Python, under Java I continued to use `_` but Eclipse warned me: `_` should not be used as an identifier, since it is a reserved keyword from source level 1.8 on. `_` will be used by lambdas, so under Java one must use something else. I will stick to `dummy`. – Jabba Oct 10 '16 at 10:37
  • Kotlin, not to leave it unmentioned, promotes _ by not issuing a compiler warning for unused variables of that name. – Ondra Žižka Dec 07 '20 at 00:07
49

I would say that it's an acceptable practice. This is a rare instance where I would consider the majority to be wrong and in need of updating their knowledge of recent programming ideas. In many languages, particularly ML-based functional languages like Haskell and OCaml, it is extremely common to use _ as an "unused" variable. Even Lua, which doesn't offer explicit language support for it, encourages the use of _ as a placeholder by convention.

Several languages (Haskell, Lua, and D I think off the top of my head) also offer a convention where variables that lead off with an underscore don't generate compiler warnings about "unused local variable" which makes _ the shortest unused variable name. You could use something like _unused but I agree with you that it just makes clutter.

CodexArcanum
  • 3,421
  • 21
  • 23
  • In the specific case of SQL, I've considered it and the coworkers may be correct here. I very commonly use a single capital letter for table aliases (and often R(esults) for subselects). I think that using `*` in selects is a very bad thing, because if the table changes your result-set changes unexpectedly as well. So I would typically need the single character alias to identify the columns I'm selecting. If you stop using `*`, you stop needing an "unused" name. – CodexArcanum May 04 '12 at 14:54
  • 12
    Strictly speaking, at least in Haskell, `_` is a pattern, not a variable. It's a subtle difference, but it means that you can use it multiple times in something like `(x, _, _) = ...`, whereas trying to bind the same variable multiple times would be an error. – hammar May 05 '12 at 01:37
15

In Python _ is definitively acceptable. It can however conflict with gettext alias _().

Other common conventions are dummy, unused; alone or as prefix.

Some code analysis tools are aware of these conventions and will not issue unused variable warnings:

  • PyLint for _ or dummy
  • PyDev for any variable starting with _, unused or dummy
vartec
  • 20,760
  • 1
  • 52
  • 98
  • 2
    Also, using `_` for dummy variables in python will clash with `_` for last returned value. E.g., in the interpreter, if you do `5*5` on line 1; then on line 2 `_` will have the value `25`. However if you then set `x,_ = (3,'not used')`, you will find that `_` is now `not used` instead of the last returned value until you `del _`. You probably shouldn't be using `_` for last returned value in real code; but its often handy in the interpreter when trying new stuff out. – dr jimbob May 04 '12 at 15:19
  • 5
    Well, `_` as last returned value works **only** in the interactive shell. – vartec May 04 '12 at 15:41
  • The same goes for Lua. Using _ is standard practice – sylvanaar May 05 '12 at 14:05
11

It depends on the ecosystem that this code is going to live in. If _ is an accepted standard to indicate "dummy variable" / "unused output", then by all means, stick with it. If it's not, find out what is and use that.

Some programming languages (e.g. Haskell) even have this 'special' identifier built into their syntax for exactly the purposes you mention.

tdammers
  • 52,406
  • 14
  • 106
  • 154
5

Careful, _ already has an intrinsic meaning in some languages

In Python:

9.6. Private Variables and Class-local References

enter link description here“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

There's also another mention in the PEP 8 (Style Guide for Python Code):

Descriptive: Naming Styles

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

In C#:

It's generally used to mark private variables that have public/internal properties. But the practice is generally looked down on these days.

In JavaScript:

There is a library called underscore.js that uses the underscore as a prefix for non-standard prototype extensions.

Example:

var object = { some:'stuff' };
var newObject = _.clone(object);

Which leads me to my point. What's wrong with the classic placeholder variable conventions.

var i, j, k, l; // iterator placeholders
var x, y, z, xx, yy, zz // value placeholders
var foo, bar, bas, fixx, buzz, qux, etc... // demonstration placeholders

Why use a custom convention that some may misinterpret when there are plenty of common conventions available already?

Evan Plaice
  • 5,725
  • 2
  • 24
  • 34
  • In Scala: it is the wildcard/placeholder symbol, but as a placeholder you can _only refer to it once_. – Rex Kerr May 04 '12 at 19:40
  • @RexKerr Interesting. Feel free to edit that into the answer if you want. I would but I'm not familiar with scala. – Evan Plaice May 04 '12 at 20:00
  • A comment should do. Anyone using Scala would know, and anyone not using Scala would probably not have Scala compatibility at the top of their list of reasons to/not to do something. – Rex Kerr May 04 '12 at 20:14
  • 1
    I think using one of those "convention" placeholders for unused variables would be a bad practice as it would make me think, first, "why the hell this guy didn't name this thing better??" and after a while I would then discover it was because the variable is not used. – igorsantos07 Apr 05 '16 at 23:00
  • @igorsantos07 I completely agree. My preference would be to give a descriptive name, even for temporary variables. The point of this answer is to demonstrate why underscore is not a good choice for a naming convention; due to its preexisting meaning in many languages. – Evan Plaice Apr 06 '16 at 16:56
2

I use "dummy" for that sort of thing. Or "crap", if I'm just testing something out :) Name your variables to describe what they are. If they're dummy, unused variables, name them as such.

1

It depends on the language. In java, yes this is bad and can be a dangerous trend to add to your code, largely because tools that use reflection don't handle underscores very well, since they are outside of java variable naming conventions. In python, this is also bad but not as bad. In clojure , its 100% okay, and in fact, its idiomatic to use _'s as place holders in a let statement.

Remember that each language has its own entire syntax and set of idioms, so you have to evaluate good/bad in terms of these idioms, rather than in absolute terms.

jayunit100
  • 379
  • 2
  • 7
  • 7
    I disagree that this is bad practice in python. It's a widely understood convention – Daenyth May 04 '12 at 17:27
  • java has taken the opinionated view that `_` is no longer supported in java9+ so I agree with OP on that point – kane Oct 21 '22 at 21:31
0

I find it to be bad practice because

  • you should not have invisible variable in your code. If you feel you should the reason could probably be discussed.

  • the Go language uses this keyword to indicate that no variable is the destination of one of the multiple returns of a function. If your language hasn't multiple returns it's not needed. Your naming convention will hurt you the day you'll use a language using _ as a standard language notation.

(I don't know Python : is this construct really needed ?)

Denys Séguret
  • 1,424
  • 1
  • 10
  • 14
  • 2
    If you use it for filtering multiple returns, then it's just consequent to also use it for dummy function arguments. In fact, there's not much difference between the two: in pattern-matching functional languages, you may write `let (a,b,_) = f(x,y,z)` just as well as `let f(x,y,_) = (g(x),h(x),g(y))`, or whatever. — And, yes, it is often useful to have dummy parameters: not as the only definition of a function, but for a polymorphic function or one with alternative pattern-matched definitions it's often the natural thing to do. – leftaroundabout May 04 '12 at 15:16
  • 1
    Your second point contradicts your main point: in Go, that essentially means the same as "I have no use for this value". – Casey Kuball May 04 '12 at 18:24
  • It is very common in python, for example when looping over the indices in an array when the elements are not important: `for i, _ in enumerate(my_list): ...` – Godsmith Jan 15 '21 at 15:20
0

It may be syntactically valid, and it might be OK as part of a standard.

With that said, it is something I would ask someone to change in a code review. I would also never put it into a coding standard, and would try to remove it from an existing one. It's just more difficult to read, and not super meaningful.

Alan Delimon
  • 440
  • 2
  • 6
0

I think it's wrong because:

1) It's harder to see as there's not many pixels.

2) If there's more than one _, how do you know which one? - or that a new developer has 'followed the rules' and kept their use extremely local in scope?

3) It's an practice that is not helpful. Using single letter variable names is so old school (i.e. my original education!). I'll see them... and then see comments added to say what the code does and that's a bad practice in today's world. I use long variables names as much as possible so everyone, regardless of programming level or familiarity with the code can just "read it" almost like english. Using 1 letter names is an extremely common practice with older code and with older programmers (again, includes me) but that does not make it ok.

junky
  • 840
  • 5
  • 12
  • 9
    "how do you know which one" _you don't_: that's exactly the point, you **don't** use the variable. So it also doesn't matter if `_` is already used in an outer scope; that one will then be shadowed (or whatever your language does in such cases), but none of them is actually used anyway. – leftaroundabout May 04 '12 at 17:44
0

To avoid namespace collisions, and allow for debugging, in case that variable name is your only clue, it might be better to call it "joined_ab_unused".

Inspired by Birfl.

Hack Saw
  • 274
  • 1
  • 5
0

Yes, it's a bad practice for two reasons:

  1. Prefixing a unused variable with an underscore isn't a widely accepted standard. It will likely be ignored the "uninitiated".
  2. I've seen some people prefix private member variables with an underscore, and your standard would greatly confuse such people.
Jim G.
  • 8,006
  • 3
  • 35
  • 66
0

What you're trying to do is to code in a nicer version of SQL which doesn't have the issue of forcing you to invent a name for something useless.

The underscore is almost invisible, so it looks like you are in that language. If only whitespace could be used as an identifier, it would be perfect, right?

But you are not in a different language, and what you're doing is not a clean way to make a language extension.

Kaz
  • 3,572
  • 1
  • 19
  • 30
0

This would be bad in perl, which uses $_ (and sometimes _) as a special variable.

In general, I'd stay away from it just because the _ seems to be a language specifmetavariable. If I saw your code, I'd be in documentation looking for what _ was, until I realized it was just a dummy. Nothing wrong with DUMMY, $DUMMY, whatever.

0

I would avoid underscores at the beginning of vars unless you were certain they didn't tend to indicate something else in a given language or framework in heavy use. For instance, in Python, a double underscore tends to indicate a magic var. In JQuery and other JS libraries a single underscore tends to indicate a fallback var for namespace overwrites. It's also a popular naming convention for include files which in turn tend to carry over to code that handles includes in var form.

Erik Reppen
  • 6,243
  • 31
  • 34