Noel Evans
Noel Evans

Reputation: 8516

Accepted convention for variable names clashing with keywords / standard libs

I have a function where I take a datetime.date and time object as arguments. Let's also say I also want an argument which needs to be named break or something very similar. I obviously can't use break as an arg without throwing a SyntaxError.

What is the most accepted renaming convention to avoid clashing with standard Python library names or keywords?

Upvotes: 5

Views: 2131

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122032

Per the style guide:

  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

    Tkinter.Toplevel(master, class_='ClassName')
    

Specifically, for arguments:

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. Thus class_ is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)

and attribute names:

  • If your public attribute name collides with a reserved keyword, append a single trailing underscore to your attribute name. This is preferable to an abbreviation or corrupted spelling. (However, notwithstanding this rule, cls is the preferred spelling for any variable or argument which is known to be a class, especially the first argument to a class method.)

Upvotes: 8

Related Questions