I am trying to execute the command abs.__ doc__
inside the exec()
function but for some reason it does not work.
function = input("Please enter the name of a function: ")
proper_string = str(function) "." "__doc__"
exec(proper_string)
Essentially, I am going through a series of exercises and one of them asks to provide a short description of the entered function using the __ doc__
attribute. I am trying with abs.__ doc__
but my command line comes empty. When I run python in the command line and type in abs.__ doc__
without anything else it works, but for some reason when I try to input it as a string into the exec()
command I can't get any output. Any help would be greatly appreciated. (I have deliberately added spaces in this description concerning the attribute I am trying to use because I get bold type without any of the underscores showing.)
As a note, I do not think I have imported any libraries that could interfere, but these are the libraries that I have imported so far:
import sys
import datetime
from math import pi
My Python version is Python 3.10.4. My operating system is Windows 10.
CodePudding user response:
abs.__doc__
is a string. You should use eval
instead of exec
to get the string.
Example:
function = input("Please enter the name of a function: ")
proper_string = str(function) "." "__doc__"
doc = eval(proper_string)
CodePudding user response:
You can access it using globals()
:
def func():
"""Func"""
pass
mine = input("Please enter the name of a function: ")
print(globals()[mine].__doc__)
globals()
return a dictionary that keeps track of all the module-level definitions. globals()[mine]
is just trying to lookup for the name stored in mine
; which is a function object if you assign mine
to "func"
.
As for abs
and int
-- since these are builtins -- you can look it up directly using getattr(abs, "__doc__")
or a more explicit: getattr(__builtins__, "abs").__doc__
.
There are different ways to lookup for a python object corresponding to a given string; it's better not to use exec
and eval
unless really needed.