Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

python - How to create separate files for functions, then import them?

I have this working code:

from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext

updater = Updater('token')

def hello(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Hello!')

updater.dispatcher.add_handler(CommandHandler('hello', hello))

updater.start_polling()
updater.idle()

I wish to have a separate file for each function and have a main.py where I import them.

So I head to create a f1.py with just this:

def hello(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Hello!')

Then import it into a main.py with

from f1 import hello
hello()

Obviously, this is not working (missing arguments). How do I do it correctly?

question from:https://stackoverflow.com/questions/65901732/how-to-create-separate-files-for-functions-then-import-them

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your main.py and f1.py are fine, but on updater.dispatcher of your main.py something is missing. Try this:

from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext

#On my bots I preffer to import the entire module than a function from a module,
#because I usually have users.py (all functions for users), clients.py (all 
#functions for clients), devs.py (all functions for developer's team) and so on
import f1

updater = Updater('token')

#Calling a function from a module must have a callback, as shown bellow
updater.dispatcher.add_handler(CommandHandler('hello', callback = f1.hello))

updater.start_polling()
updater.idle()

Try this and let me know if it worked for you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...