KyleJeong
KyleJeong

Reputation: 31

strange behavior of constant 'e' in Python

I experienced very strange behavior in Python. I am an electronics engineer. So I use constant 'e' in the equation sometimes.

from math import *

try:
    eval('print(log(e))')
except Exception as e:
    print(e)

try:
    eval('print(long(e))')
except Exception as e:
    print(e)

try:
    eval('log(e)')
except Exception as e:
    print(e)

the output is

1.0
name 'long' is not defined
name 'e' is not defined

I miss typed log(e) to long(e). Before that equation log(e) works well, but the second log(e) after long(e), the Python does not understand 'e'.

Do you have any idea what's going on there?

I am using python3.8.2 on Windows.

Upvotes: 1

Views: 1007

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122116

Setting:

except Exception as e:

shadows the imported name from math, but only if the except block is entered (i.e. an error is thrown). The reference is cleared outside the except block, but that removes any reference to e. It's equivalent to:

>>> from math import e
>>> e
2.718281828459045
>>> e = "foo"  # shadow the imported name
>>> e
'foo'
>>> del e  # try to return to previous value
>>> e
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'e' is not defined

This is also mentioned in the documentation for the try statement (emphasis mine):

When an exception has been assigned using as target, it is cleared at the end of the except clause. This is as if

except E as N:
    foo

was translated to

except E as N:
    try:
        foo
    finally:
        del N

The simplest fixes are to either:

  • rename the exception to something other than e; or
  • import math then refer to math.e (note wildcard imports are discouraged by PEP-0008).

Upvotes: 3

Zain Arshad
Zain Arshad

Reputation: 1907

So we are shadowing the variable e from the math module. In the second try-catch you are catching the exception as e, so, the e from math module get replaced by this e (exception).

You should always keep in mind that never use a variable name that is already being used by some module that you are importing etc. For example, don't use variable name list as it will shadow the built-in type list and you program will behave strangely.

In order to fix this problem, replace this:

except Exception as e:

to this:

except Exception as ex:

Upvotes: 0

Related Questions