Why does python disallow usage of hyphens within function and variable names?

Question:

I have always wondered why can’t we use hyphens in between function names and variable names in python

Having tried functional programming languages like Lisp and Clojure, where hyphens are allowed. Why python doesn’t do that.

# This won't work -- SyntaxError
def is-even(num):
    return num % 2

# This will work
def is_even(num):
    return num % 2

I am sure Sir Guido must have done this because of some reasons. I googled but couldn’t manage to find the answer. Can anyone please throw some light on this?

Asked By: aatifh

||

Answers:

Because it would make the parser even more complicated. It would be confusing too for the programmers.

Consider def is-even(num): : now, if is is a global variable, what happens?

Also note that the - is the subtraction operator in Python, hence would further complicate parsing.

Answered By: jldupont

Because hyphen is used as the subtraction operator. Imagine that you could have an is-even function, and then you had code like this:

my_var = is-even(another_var)

Is is-even(another_var) a call to the function is-even, or is it subtracting the result of the function even from a variable named is?

Lisp dialects don’t have this problem, since they use prefix notation. For example, there’s clear difference between

(is-even 4)

and

(- is (even 4))

in Lisps.

Answered By: mipadi
is-even(num)

contains a hyphen ? I thought it was a subtraction of the value returned by function even with argument num from the value of is.

As @jdupont says, parsing can be tricky.

Because Python uses infix notation to represent calculations and a hyphen and a minus has the exact same ascii code. You can have ambiguous cases such as:

a-b = 10
a = 1
b = 1

c = a-b

What is the answer? 0 or 10?

Answered By: JPvdMerwe

Oddly enough it is possible to have class variable names with hyphens using setattr(), not that you would want to. Here is an example:

class testclass:
    pass

x = testclass()
setattr(x, "is-even", True)
getattr(x, "is-even")
True

This still fails:

x.is-even
File "<stdin>", line 1
  x.is-even
     ^
SyntaxError: invalid syntax
Answered By: pekowski
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.