简体   繁体   中英

How to import just a single constant or function from a library?

I have a script that uses a single constant from the library string. Instead of importing the whole library, which seems like overkill, can I import just this constant? Is there more than one way?

I tried

from string import ascii_letters

which worked when I also fixed the name in my code ( string.ascii_letters became ascii_letters ). I would also like to import just a single function from the library random . My experiments just game me syntax errors. Is this possible, or do I need the whole library/module to get the functions in it? I couldn't find the answer in the documentation for the import system.

The syntax errors you mentioned are either in the script you import to or the module itself.
If it's in the module, we have to see it to know whats wrong, but I'll assume you've tested that mod.
That leaves us with your current script. The Line import name , long as name exists (locally), would not trigger syntax errors. same with the format

from name import something

This makes me think that your problem is somewhere else, and if you can add you code then it might be possible to help. (to clarify - importing just one const, function, etc. will not triggera syntax error, given you have typed the right names).

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