Is it possible to escape a reserved word in Python?

前端 未结 5 1569
一整个雨季
一整个雨季 2020-12-18 04:36

It may not be a good idea to name a variable after a reserved word, but I am curious:

Is there any escape syntax in Python to allow you to use a reserved word as the

相关标签:
5条回答
  • 2020-12-18 05:20

    If you don't mind prefixing, you can "prefix" with an underscore. Sure it'll actually be part of the variable's name, but it'll look like a prefixed reserved word. Other than that, it is not possible.

    0 讨论(0)
  • 2020-12-18 05:22

    No, this is not possible.

    Section 2.3.1 of The Python Language Reference says that keywords 'cannot be used as ordinary identifiers' and does not specify an escape syntax.

    This is probably a Good Thing, for the sake of code readability!

    0 讨论(0)
  • 2020-12-18 05:29

    I received an error when using the following:

    for r in db.call ('ReadCashflows',
                      number = number,
                      from = date_from,
                      to = date_to):
    

    I tried using capitals instead and now it works:

    for r in db.call ('ReadCashflows',
                      number = number,
                      FROM = date_from,
                      TO = date_to):
    

    This was possible for me because my database is ORACLE (which is case-insensitive). Remark on the code above: in my software application the actual parameters in the database are pFROM and pTO; the "p" gets added in the post-processing before the call to the database is made.

    0 讨论(0)
  • 2020-12-18 05:31

    It is not possible, however it is some kind of a tradition in Python to append a _ to get a new identifier:

    def drive(from_, to):
        pass
    
    0 讨论(0)
  • 2020-12-18 05:41
    db.call( ..., **{ 'from' : date_from }, **{ 'to' : date_to })
    

    Python doesn't do those check when unpacking.

    0 讨论(0)
提交回复
热议问题