简体   繁体   中英

Python import function with package

I want to import a function from another python file. The problem is that I either have to call it with file.function() or import it with from file import function .

Since my file contains only one function, I am looking for a way to import it directly with import file .

I don't understand the problem. Why not just:

from file import function

function(params)

Not sure why from file import function is an issue, but the only other way to do it (other than calling file.function() everythime) is to do from file import *

Not sure what the issue is with either option that you listed.

What you can do is turn your module (the file with the function you want to import) into a script by adding if __name__ == "__main__": to the end of your file like so:

# file.py
def function(...):
    ...

if __name__ == "__main__":
    import sys
    function(sys.argv[1])

then import it as import file .

Reference: https://docs.python.org/3/tutorial/modules.html#executing-modules-as-scripts

I personally don't see an issue with alternative you listed, but the docs do have this to say about what you're trying to achieve:

This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).

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