5

In the twilio python library, we have this feature to create messages:

from twilio.rest import TwilioRestClient

and we can write:

msg = TwilioRestClient.messages.create(body=myMsgString, from_=myNumber, to=yourNumber)

My question is simple: why does an underscore follow the from parameter? Or why is that the parameter name? Is it because from is otherwise a keyword in Python and we differentiate variables from keywords with an underscore suffix? Is that actually necessary in this case?

Megan Speir
  • 3,745
  • 1
  • 15
  • 25
Newb
  • 2,810
  • 3
  • 21
  • 35
  • 2
    You've answered yourself. You can't use `from` as it's a keyword. [PEP8](https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles) suggests doing this and gives the example of `class_`. – Holloway Aug 01 '16 at 22:04

1 Answers1

12

This is because from would be an invalid argument name, resulting in a SyntaxError - it's a python keyword.

Appending a trailing underscore is the recommended way to avoid such conflicts mentioned in the PEP8 style guide:

If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption.

wim
  • 338,267
  • 99
  • 616
  • 750
  • 1
    Hey wim, thanks for your answer here! One of my favorite gotchas in the Twilio-Python helper library ;) Can I offer you a shirt for your contribution to the community? Send an email to mspeir@twilio.com for details. – Megan Speir Aug 23 '16 at 00:10
  • 1
    Hey, I received [the t-shirt](http://i.stack.imgur.com/oQQF7.jpg). Cheers! – wim Sep 09 '16 at 17:28