简体   繁体   中英

How can I define a function called “import” in Python?

Im writing a small python commandline tool which can import some data.

Usage looks like

./cli.py export -p
./cli.py import -p

Obviously, "import" conflicts with the normal import statment. So the function looks like

@click.command(short_help="Imports all documents",
@click.option('password', '-p')
def import(password):    
    coll = db.get_document_collection()

Since im using click library for parsing/building my commandline options, each function gets imported with its name. But when i execute it, it fails.

   def import(password):
            ^
   SyntaxError: invalid syntax

TLDR; How can I specify a function that is already defined by python internals?

Renaming the function without changing click 's options would indeed rename your subcommand. However, click lets you use any function name you'd like, and provide the subcommand name you want to associate with it.

For example, this will give you the subcommand import which will run the function my_import_func :

#!/usr/bin/env python3

import click

@click.group()
def cli():
    pass

@cli.command('import')
def my_import_func():
    click.echo("Importing")

if __name__ == '__main__':
    cli()

Redefining built-in names is a bad idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM