How does python import modules




















Next, we use the import keyword and call the specific function we would like to use. Now, when we implement this function within our program, we will no longer write the function in dot notation as random.

It is possible to modify the names of modules and their functions within Python by using the as keyword. You may want to change a name because you have already used the same name for something else in your program, another module you have imported also uses that name, or you may want to abbreviate a longer name that you are using a lot. Our modified program will look like this:. Within the program, we now refer to the pi constant as m.

For some modules, it is commonplace to use aliases. The matplotlib. This allows programmers to append the shorter word plt to any of the functions available within the module, as in plt.

Some modules are installed as part of Python, and some we will install through pip. We can also create our own modules for ourselves and for other programmers to use in future programs. Python is a flexible and versatile programming language that can be leveraged for many use cases, with strengths in scripting, automation, data analysis, machine learning, and back-end development. It is a great tool for both new learners and experienced developers alike. Where would you like to share this to?

Twitter Reddit Hacker News Facebook. Share link Tutorial share link. Sign Up. DigitalOcean home. Community Control Panel. Hacktoberfest Contribute to Open Source. How To Code in Python. Suppose we want to import the time module into your code. We are going to import the time module and give it the alias t. The time library has been given the alias t.

When we want to reference any function in the time library, we must use t and the dot notation. Importing modules is an important part of working with Python that allows you to call functions that are not part of your main program.

The modules you work with can be part of Python, installed using pip, or created by you. For a challenge, try to import the Python logging module into your code. Then, try to import the random. Do not import the whole module. After you have imported the randint function, check if you have imported the module successfully. You can do this using the following code:. This tutorial discussed, with examples, the basics of Python modules and how to import them in your code.

For guidance on the best Python learning resources, courses, and books, check out our comprehensive How to Learn Python guide. About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication. James Gallagher is a self-taught programmer and the technical content manager at Career Karma. James has written hundreds of programming tutorials, and he frequently contributes to publications like Codecademy, Treehouse, Repl.

He also serves as a researcher at Career Karma, publishing comprehensive reports on the bootcamp market. Read more by James Gallagher. With help from Career Karma, you can find a training program that meets your needs and will set you up for a long-term, well-paid career in tech. Find the right bootcamp for you. By continuing you agree to our Terms of Service and Privacy Policy , and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Find a top-rated training program. This is an error unless the replacement is intended. See section Standard Modules for more information. For example, in CPython release 3. This naming convention allows compiled modules from different releases and different versions of Python to coexist. This is a completely automatic process.

Also, the compiled modules are platform-independent, so the same library can be shared among systems with different architectures. Python does not check the cache in two circumstances. Second, it does not check the cache if there is no source module. To support a non-source compiled only distribution, the compiled module must be in the source directory, and there must not be a source module.

You can use the -O or -OO switches on the Python command to reduce the size of a compiled module. Future releases may change the effects of optimization. The module compileall can create. There is more detail on this process, including a flow chart of the decisions, in PEP Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls.

The set of such modules is a configuration option which also depends on the underlying platform. For example, the winreg module is only provided on Windows systems. One particular module deserves some attention: sys , which is built into every Python interpreter.

The variables sys. The variable sys. You can modify it using standard list operations:. The built-in function dir is used to find out which names a module defines. It returns a sorted list of strings:. Without arguments, dir lists the names you have defined currently:. If you want a list of those, they are defined in the standard module builtins :. For example, the module name A.

B designates a submodule named B in a package named A. There are many different sound file formats usually recognized by their extension, for example:. There are also many different operations you might want to perform on sound data such as mixing, adding echo, applying an equalizer function, creating an artificial stereo effect , so in addition you will be writing a never-ending stream of modules to perform these operations. If sys. Any other exceptions raised are simply propagated up, aborting the import process.

The first is the fully qualified name of the module being imported, for example foo. The second argument is the path entries to use for the module search. The third argument is an existing module object that will be the target of loading later. The import system passes in a target module only during reload.

The meta path may be traversed multiple times for a single import request. For example, assuming none of the modules involved has already been cached, importing foo.

After foo has been imported, foo. Once foo. Some meta path finders only support top level imports. These importers will always return None when anything other than None is passed as the second argument. If and when a module spec is found, the import machinery will use it and the loader it contains when loading the module.

Here is an approximation of what happens during the loading portion of import:. If there is an existing module object with the given name in sys. The module will exist in sys. This is crucial because the module code may directly or indirectly import itself; adding it to sys. If loading fails, the failing module — and only the failing module — gets removed from sys.

Any module already in the sys. This contrasts with reloading where even the failing module is left in sys. Execution is entirely delegated to the loader, which gets to decide what gets populated and how.

These were previously performed by the importlib. Module loaders provide the critical function of loading: module execution. The import machinery calls the importlib. It takes one argument, the module spec, and returns the new module object to use during loading. If the method returns None , the import machinery will create the new module itself. New in version 3. All the same constraints apply, with some additional clarification:.

Otherwise, importlib. If the named module does not exist in sys. The module must exist in sys. If loading fails, the loader must remove any modules it has inserted into sys. When a submodule is loaded using any mechanism e. For example, if package spam has a submodule foo , after importing spam. The invariant holding is that if you have sys.

The import machinery uses a variety of information about each module during import, especially before loading. Most of the information is common to all modules. Using a spec during import allows state to be transferred between import system components, e. Most importantly, it allows the import machinery to perform the boilerplate operations of loading, whereas without a module spec the loader had that responsibility.

See ModuleSpec for details on the contents of the module spec. This name is used to uniquely identify the module in the import system. This is mostly for introspection, but can be used for additional loader-specific functionality, for example getting data associated with a loader.

See PEP for further details. The file does not need to exist to set this attribute; the path can simply point to where the compiled file would exist see PEP However, that scenario is quite atypical. So if a loader can load from a cached module but otherwise does not load from a file, that atypical scenario may be appropriate. Within the import machinery, it functions much the same as sys.

The same rules used for sys. If that fails or there is no spec, the import system will craft a default repr using whatever information is available on the module. It will try to use the module. For backward compatibility with Python 3. However, the method is deprecated. Before Python loads cached bytecode from a. There are two variants of hash-based. For checked hash-based. If a checked hash-based cache file is found to be invalid, Python regenerates it and writes a new checked hash-based cache file.

For unchecked hash-based.



0コメント

  • 1000 / 1000