0

I have come across such a coding style for cases when a tuple is returned.

_, number_of_days_in_month = calendar.monthrange(year, month)

In this case monthrange returns a tuple with two values: weekday of first day of the month and number of days in month.

  1. Is this style acceptable? Is it described in some famous style guides like Google Python Style Guide?

  2. What should I do if _ is already occupied? For example, in Django it is used for translation like this:

    from django.utils.translation import ugettext as _
    output = _("Welcome to my site.")
    
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Michael
  • 4,273
  • 3
  • 40
  • 69
  • 1
    The `_` is commonly used to store return values you don't intend to use - it's just a convention, so you can replace it with any other valid identifier – UnholySheep Jun 11 '17 at 10:12
  • 1
    That being said, importing a function `as _` seems bad style IMO - it makes the usage of that function unclear and obscure – UnholySheep Jun 11 '17 at 10:13
  • 2
    What kind of genius came up with the idea to name `gettext` `_` anyway? – Aran-Fey Jun 11 '17 at 10:13
  • It's a pretty common pattern, even mentioned in the docs: https://docs.python.org/3/library/gettext.html#gettext.gettext – jonrsharpe Jun 11 '17 at 10:15
  • @Rawing, this is in the documentation. https://docs.djangoproject.com/en/1.11/topics/i18n/translation/ Anyway this is already a well established practice in Django. So, what could you suggest to me? – Michael Jun 11 '17 at 10:16
  • Possible duplicate of [What is the purpose of the single underscore "\_" variable in Python?](https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python) – zwer Jun 11 '17 at 10:16
  • I'm aware it's a common pattern, I'm just wondering _why_. – Aran-Fey Jun 11 '17 at 10:17
  • 1
    Usually `_` is seen as a throwaway variable. For instance a python interactive shell uses `_` to store the *last* result. The fact that some libraries use `_` is actually a bad practice. – Willem Van Onsem Jun 11 '17 at 10:17
  • @Rawing it comes from C; it is a name without use in C, and `_` is less to type than `gettext`; [gettext documentation](https://www.gnu.org/software/gettext/manual/html_node/Mark-Keywords.html#Mark-Keywords). Note that there is no official use for `_` in Python either, just some conventions and a special behaviour in the REPL. – Antti Haapala -- Слава Україні Jun 11 '17 at 10:21

1 Answers1

0

I think, we sould follow the advice from The Hitchhiker’s Guide to Python:

http://python-guide-pt-br.readthedocs.io/en/latest/writing/style/#create-an-ignored-variable

That is: use __ in this case.

Michael
  • 4,273
  • 3
  • 40
  • 69