Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the function names of functions in a separate file?

Tags:

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!

like image 728
Neemaximo Avatar asked Jul 12 '18 18:07

Neemaximo


People also ask

How do you call a function from another file?

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.

Should Python functions be in separate files?

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.

How do I print a function name?

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.

How do I call a class function from another file in Python?

Create another Python file and import the previous Python file into it. Call the functions defined in the imported file.


1 Answers

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']
like image 110
rafaelc Avatar answered Sep 28 '22 19:09

rafaelc