I am creating a chatbot that has 2 main files, main.py
which runs the bot and commands.py
which contains the commands the bot recognizes. I am trying to get the function names from commands.py
in order to use that information (as a simple string/store as a variable) in main.py
. For example:
commands.py
def add():
pass
def delete():
pass
def change():
pass
Basically, I want to be able to store in a variable commands = ['add', 'delete', 'change']
or something similar. I don't have any experience with decorators, but is this possibly a good time to use it? To be able to register commands with a decorator? I'm open to any suggestions, thanks!
To use the functions written in one file inside another file include the import line, from filename import function_name . Note that although the file name must contain a . py extension, . py is not used as part of the filename during import.
As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you've written in several programs without copying its definition into each program.
In this program, we will use __FUNCTION__ macro to print the function name, also we will print all function names defined in the source code. __FUNCTION__ Macro: This macro is used to return the current function name. It is useful for debugging i.e., to generate the logs.
Create another Python file and import the previous Python file into it. Call the functions defined in the imported file.
IIUC,
import commands
>>> dir(commands)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'add',
'delete',
'change']
Then filter out the magic attrs
>>> function_names = [func for func in dir(commands) if not func.startswith('__')]
['add', 'delete', 'change']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With