Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

People also ask

Is hyphen allowed in Python variable?

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.

Is hyphen allowed in variable name?

Hyphens are used as subtraction and negation operators, so they cannot be used in variable names.

What makes a variable name illegal in Python?

Rules for Python variables: A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

Which of the following Cannot be used as variable names in Python?

Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language.


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.


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?


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.


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.