1

I am new with python and PyCharm. The following code works in python console, listing the functions in the math package:

import importlib
st = 'math'
importlib.import_module(st)
dir(eval(st))

However, if the same snippet appears in the editor window and runs, the below message shows:

Traceback (most recent call last):
  File "C:/Users/sywan/PycharmProjects/test/test.py", line 4, in <module>
    dir(eval(st))
  File "<string>", line 1, in <module>
NameError: name 'math' is not defined

Your answer is very much appreciated!!

Shu-Yen
  • 31
  • 4

1 Answers1

1

This so answer explains what does eval do

eval interprets a string as code. In your case eval convert 'math' into math and search for a variable named math.

import importlib
st = 'math'
dir_path = importlib.import_module(st)
dir(dir_path) 

To find functions in math module, save module path in variable and then apply dir method as importlib.import_module(st) return st directory path

Community
  • 1
  • 1
sid
  • 97
  • 12