如何为Python包(特指KERAS)创建别名?需避免代码显式引用KERAS
I get it—you want to use a custom alias for Keras so your code can call it by a different name without having to write import keras or reference keras directly. Modifying the setup.py in the Keras repo and reinstalling didn't work, which makes sense because Keras's internal module structure is tightly tied to its official package name. Let's walk through two reliable, Python 3-compatible solutions that work globally and don't require changing your project code:
Solution 1: Create an Alias Module in site-packages
This method creates a dummy package that acts as a direct proxy for Keras. Here's how to set it up:
- First, find your Python environment's
site-packagesdirectory (where third-party packages are installed). Run this command in your terminal:python -c "import site; print(site.getsitepackages())" - Navigate to one of the paths listed (usually the first one for your active environment).
- Create a new folder named after your desired alias (e.g.,
mykeras). - Inside this folder, create an
__init__.pyfile with the following code:# Mirror Keras's entire namespace in the alias package import keras __all__ = keras.__all__ __dict__.update(keras.__dict__)
Now, whenever you write import mykeras or from mykeras.layers import Dense in your code, it will behave exactly like using keras directly.
Solution 2: Use sys.modules for Global Module Mapping
This approach maps your alias directly to the Keras module in Python's module registry, loading automatically every time you start Python. It's cleaner and avoids creating extra files in site-packages:
- Find your user-specific
site-packagesdirectory (safer than modifying global directories, especially for virtual environments):python -c "import site; print(site.getusersitepackages())" - If the directory doesn't exist, create it. Then, inside it, create a file named
usercustomize.py(this file runs automatically when Python starts). - Add this code to
usercustomize.py:import sys import keras # Map your alias to the Keras module sys.modules['mykeras'] = keras
That's it! From now on, any import using your alias will point directly to the Keras module. For example:
import mykeras model = mykeras.Sequential()
Works exactly the same as:
import keras model = keras.Sequential()
Why Modifying setup.py Didn't Work
When you changed the package name in Keras's setup.py, you were trying to rename the entire package—but Keras's internal code, dependencies, and even some third-party libraries rely on the keras module name. This approach breaks the package's internal references and doesn't create a proper alias; it just installs a renamed version that won't function correctly with existing code.
内容的提问来源于stack exchange,提问作者Pavithran Ravichandiran

