Bypassing import in Python so that I don't have to upload multiple libraries and classes?
For example, I have a few python scripts, that link together and some libraries for it that need to be imported. I'm trying to reduce it to only one script.
So instead of:
import library.py
Can 开发者_C百科I just take the coding from library.py and put into the main script?
There are no limits to the size of a .py
file, so you can certainly perform the copy and paste (and edit) operations you have in mind.
Some caveats:
import library.py
is unlikely to do what you want: it imports a module named py
from a package named library
. Thus it requires the existence of a directory library
with an __init__.py
and a py.py
in it (or .pyc
, etc). I suspect you mean import library
.
Merging all the needed modules into one large .py
file only works for modules for which you have Python sources (.py
) -- you need different techniques if all you have for a module is bytecode .pyc
or .pyo
, and if any of the modules are native-code binary Python extensions (.pyd
or .so
or .dylib
etc etc, depending on your system) that just won't work.
You may have to do some renaming, e.g. when you import two modules that both define name foo
you'll have to alter one or both of those names foo
. That's because, via imports, you get qualified names (so there's no problem if a.foo
and b.foo
both exist), but without imports you get bare names so you'll need to disambiguate them "manually".
Yes you can do this, but probably it won't increase readability or maintainability.
Anyway be careful if you use functions like this:
import library
library.functionA()
If you copy the content of library.py
, you have to rename the function call to just functionA()
.
精彩评论