Is there a reason why Python developers (both maintainers of Python itself and authors of modules) tend to pass special strings as arguments to functions instead of defining symbols for the same purpose? Rather than make other developers look up or guess the special values allowed for some arguments, why not define symbols to represent them?
The simplest example of this I can think of in base Python is the open()
function. To specify the mode in which a file is opened, the mode
argument can take one of several string values. For example, to open a file for writing:
fileObject = open('/tmp/tarfu.txt', 'w')
Why not define symbols to represent the values allowed for mode
? That is, constants, enumerations, class members, or something similar.
A simple definition could be added to the same module that defines open()
(io
, I believe):
OPEN_MODE_WRITE = 'w'
Then it could be used with open()
:
fileObject = open('/tmp/tarfu.txt', OPEN_MODE_WRITE)
That would be similar to other languages, like PHP, Java, C, and others. Although the corresponding file open functions of those other languages may not be examples of the ideal, those languages have more examples of it than Python. They all commonly define symbols for such purposes. Using them helps make getting the right value easier, especially if the developer's editor has features to autocomplete or suggest symbols. If the symbols are of a specific type (as in enumerations or class members), then the types of the arguments can be checked, too.
By using strings for these special values, mistakes in code may only be detected at runtime, which may be difficult to trace back to the offending code. Using symbols would also make code easier to understand, which I believe would make it more Pythonic.
Everything I've written here in reference to strings applies to numbers as well. I was inspired to write this question after using pandas for a while. Several of its functions allow the developer to specify whether an operation applies to rows or columns of a DataFrame
object by supplying the numbers 0
and 1
or the strings rows
and columns
for the axis
argument. I'd rather it have symbols like AXIS_ROWS
and AXIS_COLUMNS
defined for this purpose.