A package is a container that contains various functions to perform specific tasks. For example, the Show
While working on big projects, we have to deal with a large amount of code, and writing everything together in the same file will make our code look messy. Instead, we can separate our code into multiple files by keeping the related code together in packages. Now, we can use the package whenever we need it in our projects. This way we can also reuse our code. Package Model Structure in Python ProgrammingSuppose we are developing a game. One possible organization of packages and modules could be as shown in the figure below. Game Package Model StructureNote: A directory must contain a file named Importing module from a packageIn Python, we can import modules from packages using the dot (.) operator. For example, if we want to import the
Now, if this module contains a function named 0, we must use the full name to reference it.
Import Without Package PrefixIf this construct seems lengthy, we can import the module without the package prefix as follows:
We can now call the function simply as follows:
Import Required Functionality OnlyAnother way of importing just the required function (or class or variable) from a module within a package would be as follows:
Now we can directly call this function.
Although easier, this method is not recommended. Using the full namespace avoids confusion and prevents two same identifier names from colliding. While importing packages, Python looks in the list of directories defined in 1, similar as for . This article explores Python modules and Python packages, two mechanisms that facilitate modular programming. Modular programming refers to the process of breaking a large, unwieldy programming task into separate, smaller, more manageable subtasks or modules. Individual modules can then be cobbled together like building blocks to create a larger application. There are several advantages to modularizing code in a large application:
Functions, modules and packages are all constructs in Python that promote code modularization. Free PDF Download: Python 3 Cheat Sheet Python Modules: OverviewThere are actually three different ways to define a module in Python:
A module’s contents are accessed the same way in all three cases: with the 8 statement.Here, the focus will mostly be on modules that are written in Python. The cool thing about modules written in Python is that they are exceedingly straightforward to build. All you need to do is create a file that contains legitimate Python code and then give the file a name with a 9 extension. That’s it! No special syntax or voodoo is necessary.For example, suppose you have created a file called 0 containing the following:mod.py
Several objects are defined in 0:
Assuming 0 is in an appropriate location, which you will learn more about shortly, these objects can be accessed by importing the module as follows:>>> Remove adsThe Module Search PathContinuing with the above example, let’s take a look at what happens when Python executes the statement:
When the interpreter executes the above 8 statement, it searches for 0 in a list of directories assembled from the following sources:
The resulting search path is accessible in the Python variable 2, which is obtained from a module named 3:>>>
Note: The exact contents of 2 are installation-dependent. The above will almost certainly look slightly different on your computer.Thus, to ensure your module is found, you need to do one of the following:
There is actually one additional option: you can put the module file in any directory of your choice and then modify 2 at run-time so that it contains that directory. For example, in this case, you could put 0 in directory 03 and then issue the following statements:>>>
Once a module has been imported, you can determine the location where it was found with the module’s 04 attribute:>>>
The directory portion of 04 should be one of the directories in 2.The >>> import mod >>> mod <module 'mod' from 'C:\\Users\\john\\Documents\\Python\\doc\\mod.py'> 8 StatementModule contents are made available to the caller with the 8 statement. The 8 statement takes many different forms, shown below.>>> import mod >>> print(mod.s) If Comrade Napoleon says it, it must be right. >>> mod.a [100, 200, 300] >>> mod.foo(['quux', 'corge', 'grault']) arg = ['quux', 'corge', 'grault'] >>> x = mod.Foo() >>> x <mod.Foo object at 0x03C181F0> 10The simplest form is the one already shown above:
Note that this does not make the module contents directly accessible to the caller. Each module has its own private symbol table, which serves as the global symbol table for all objects defined in the module. Thus, a module creates a separate namespace, as already noted. The statement 10 only places 12 in the caller’s symbol table. The objects that are defined in the module remain in the module’s private symbol table.From the caller, objects in the module are only accessible when prefixed with 12 via dot notation, as illustrated below.After the following 8 statement, 15 is placed into the local symbol table. Thus, 15 has meaning in the caller’s local context:>>>
But 2 and 18 remain in the module’s private symbol table and are not meaningful in the local context:>>>
To be accessed in the local context, names of objects defined in the module must be prefixed by 15:>>>
Several comma-separated modules may be specified in a single 8 statement: 0Remove ads>>> import mod >>> print(mod.s) If Comrade Napoleon says it, it must be right. >>> mod.a [100, 200, 300] >>> mod.foo(['quux', 'corge', 'grault']) arg = ['quux', 'corge', 'grault'] >>> x = mod.Foo() >>> x <mod.Foo object at 0x03C181F0> 21An alternate form of the 8 statement allows individual objects from the module to be imported directly into the caller’s symbol table: 1Following execution of the above statement, 23 can be referenced in the caller’s environment without the 12 prefix:>>> 2Because this form of 8 places the object names directly into the caller’s symbol table, any objects that already exist with the same name will be overwritten:>>> 3It is even possible to indiscriminately 8 everything from a module at one fell swoop: 4This will place the names of all objects from 12 into the local symbol table, with the exception of any that begin with the underscore ( 28) character.For example: >>> 5This isn’t necessarily recommended in large-scale production code. It’s a bit dangerous because you are entering names into the local symbol table en masse. Unless you know them all well and can be confident there won’t be a conflict, you have a decent chance of overwriting an existing name inadvertently. However, this syntax is quite handy when you are just mucking around with the interactive interpreter, for testing or discovery purposes, because it quickly gives you access to everything a module has to offer without a lot of typing. >>> import mod >>> print(mod.s) If Comrade Napoleon says it, it must be right. >>> mod.a [100, 200, 300] >>> mod.foo(['quux', 'corge', 'grault']) arg = ['quux', 'corge', 'grault'] >>> x = mod.Foo() >>> x <mod.Foo object at 0x03C181F0> 29It is also possible to 8 individual objects but enter them into the local symbol table with alternate names: 6This makes it possible to place names directly into the local symbol table but avoid conflicts with previously existing names: >>> 7>>> import mod >>> print(mod.s) If Comrade Napoleon says it, it must be right. >>> mod.a [100, 200, 300] >>> mod.foo(['quux', 'corge', 'grault']) arg = ['quux', 'corge', 'grault'] >>> x = mod.Foo() >>> x <mod.Foo object at 0x03C181F0> 31You can also import an entire module under an alternate name: 8>>> 9Module contents can be imported from within a function definition. In that case, the 8 does not occur until the function is called:>>> 0However, Python 3 does not allow the indiscriminate 33 syntax from within a function:>>> 1Lastly, a 34 statement with an 35 clause can be used to guard against unsuccessful 8 attempts:>>> 2>>> 3Remove adsThe >>> import mod >>> print(mod.s) If Comrade Napoleon says it, it must be right. >>> mod.a [100, 200, 300] >>> mod.foo(['quux', 'corge', 'grault']) arg = ['quux', 'corge', 'grault'] >>> x = mod.Foo() >>> x <mod.Foo object at 0x03C181F0> 37 FunctionThe built-in function 37 returns a list of defined names in a namespace. Without arguments, it produces an alphabetically sorted list of names in the current local symbol table:>>> 4Note how the first call to 37 above lists several names that are automatically defined and already in the namespace when the interpreter starts. As new names are defined ( 40, 41, 42), they appear on subsequent invocations of 37.This can be useful for identifying what exactly has been added to the namespace by an import statement: >>> 5When given an argument that is the name of a module, 37 lists the names defined in the module:>>> 6>>> 7Executing a Module as a ScriptAny 9 file that contains a module is essentially also a Python script, and there isn’t any reason it can’t be executed like one.Here again is 0 as it was defined above:mod.py
This can be run as a script: 9There are no errors, so it apparently worked. Granted, it’s not very interesting. As it is written, it only defines objects. It doesn’t do anything with them, and it doesn’t generate any output. Let’s modify the above Python module so it does generate some output when run as a script: mod.py 0Now it should be a little more interesting: 1Unfortunately, now it also generates output when imported as a module: >>> 2This is probably not what you want. It isn’t usual for a module to generate output when it is imported. Wouldn’t it be nice if you could distinguish between when the file is loaded as a module and when it is run as a standalone script? Ask and ye shall receive. When a 9 file is imported as a module, Python sets the special dunder variable 48 to the name of the module. However, if a file is run as a standalone script, 48 is (creatively) set to the string 50. Using this fact, you can discern which is the case at run-time and alter behavior accordingly:mod.py 3Now, if you run as a script, you get output: 4But if you import as a module, you don’t: >>> 5Modules are often designed with the capability to run as a standalone script for purposes of testing the functionality that is contained within the module. This is referred to as unit testing. For example, suppose you have created a module 51 containing a factorial function, as follows:fact.py 6The file can be treated as a module, and the 52 function imported:>>> 7But it can also be run as a standalone by passing an integer argument on the command-line for testing: 8Remove adsReloading a ModuleFor reasons of efficiency, a module is only loaded once per interpreter session. That is fine for function and class definitions, which typically make up the bulk of a module’s contents. But a module can contain executable statements as well, usually for initialization. Be aware that these statements will only be executed the first time a module is imported. Consider the following file 0:mod.py 9>>> 0The 54 statement is not executed on subsequent imports. (For that matter, neither is the assignment statement, but as the final display of the value of 55 shows, that doesn’t matter. Once the assignment is made, it sticks.)If you make a change to a module and need to reload it, you need to either restart the interpreter or use a function called 56 from module 57:>>> 1Python PackagesSuppose you have developed a very large application that includes many modules. As the number of modules grows, it becomes difficult to keep track of them all if they are dumped into one location. This is particularly so if they have similar names or functionality. You might wish for a means of grouping and organizing them. Packages allow for a hierarchical structuring of the module namespace using dot notation. In the same way that modules help avoid collisions between global variable names, packages help avoid collisions between module names. Creating a package is quite straightforward, since it makes use of the operating system’s inherent hierarchical file structure. Consider the following arrangement: Here, there is a directory named 58 that contains two modules, 59 and 60. The contents of the modules are:mod1.py 2mod2.py 3Given this structure, if the 58 directory resides in a location where it can be found (in one of the directories contained in 2), you can refer to the two modules with dot notation ( 63, 64) and import them with the syntax you are already familiar with: 0>>> 5 1>>> 7 8>>> 9You can import modules with these statements as well: 0>>> 1You can technically import the package as well: >>> 2But this is of little avail. Though this is, strictly speaking, a syntactically correct Python statement, it doesn’t do much of anything useful. In particular, it does not place any of the modules in 58 into the local namespace:>>> 3To actually import the modules or their contents, you need to use one of the forms shown above. Remove adsPackage InitializationIf a file named 66 is present in a package directory, it is invoked when the package or a module in the package is imported. This can be used for execution of package initialization code, such as initialization of package-level data.For example, consider the following 66 file:__init__.py 4Let’s add this file to the 58 directory from the above example:Now when the package is imported, the global list 69 is initialized:>>> 5A module in the package can access the global variable by importing it in turn: mod1.py 6>>> 7 66 can also be used to effect automatic importing of modules from a package. For example, earlier you saw that the statement 71 only places the name 58 in the caller’s local symbol table and doesn’t import any modules. But if 66 in the 58 directory contains the following:__init__.py 8then when you execute 71, modules 76 and 77 are imported automatically:>>> 9Note: Much of the Python documentation states that an 66 file must be present in the package directory when creating a package. This was once true. It used to be that the very presence of 66 signified to Python that a package was being defined. The file could contain initialization code or even be empty, but it had to be present.Starting with Python 3.3, Implicit Namespace Packages were introduced. These allow for the creation of a package without any 66 file. Of course, it can still be present if package initialization is needed. But it is no longer required.Importing >>> import mod >>> print(mod.s) If Comrade Napoleon says it, it must be right. >>> mod.a [100, 200, 300] >>> mod.foo(['quux', 'corge', 'grault']) arg = ['quux', 'corge', 'grault'] >>> x = mod.Foo() >>> x <mod.Foo object at 0x03C181F0> 81 From a PackageFor the purposes of the following discussion, the previously defined package is expanded to contain some additional modules: There are now four modules defined in the 58 directory. Their contents are as shown below:mod1.py 2mod2.py 3mod3.py 2mod4.py 3(Imaginative, aren’t they?) You have already seen that when 33 is used for a module, all objects from the module are imported into the local symbol table, except those whose names begin with an underscore, as always:>>> 4The analogous statement for a package is this: 5What does that do? >>> 6Hmph. Not much. You might have expected (assuming you had any expectations at all) that Python would dive down into the package directory, find all the modules it could, and import them all. But as you can see, by default that is not what happens. Instead, Python follows this convention: if the 66 file in the package directory contains a list named 85, it is taken to be a list of modules that should be imported when the statement 86 is encountered.For the present example, suppose you create an 66 in the 58 directory like this:pkg/__init__.py 7Now 89 imports all four modules:>>> 8Using 33 still isn’t considered terrific form, any more for packages than for modules. But this facility at least gives the creator of the package some control over what happens when 33 is specified. (In fact, it provides the capability to disallow it entirely, simply by declining to define 85 at all. As you have seen, the default behavior for packages is to import nothing.)By the way, 85 can be defined in a module as well and serves the same purpose: to control what is imported with 33. For example, modify 59 as follows:pkg/mod1.py 9Now an 33 statement from 63 will only import what is contained in 85:>>> 0 4 (the function) is now defined in the local namespace, but 5 (the class) is not, because the latter is not in 85.In summary, 85 is used by both packages and modules to control what is imported when 33 is specified. But the default behavior differs:
SubpackagesPackages can contain nested subpackages to arbitrary depth. For example, let’s make one more modification to the example package directory as follows: The four modules ( 59, 60, 10 and 11) are defined as previously. But now, instead of being lumped together into the 58 directory, they are split out into two subpackage directories, 13 and 14.Importing still works the same as shown previously. Syntax is similar, but additional dot notation is used to separate package name from subpackage name: >>> 1In addition, a module in one subpackage can reference objects in a sibling subpackage (in the event that the sibling contains some functionality that you need). For example, suppose you want to import and execute function 4 (defined in module 76) from within module 17. You can either use an absolute import:pkg/sub__pkg2/mod3.py 2>>> 3Or you can use a relative import, where 18 refers to the package one level up. From within 10, which is in subpackage 14,
pkg/sub__pkg2/mod3.py 4>>> 5ConclusionIn this tutorial, you covered the following topics:
Free PDF Download: Python 3 Cheat Sheet This will hopefully allow you to better understand how to gain access to the functionality available in the many third-party and built-in modules available in Python. Additionally, if you are developing your own application, creating your own modules and packages will help you organize and modularize your code, which makes coding, maintenance, and debugging easier. If you want to learn more, check out the following documentation at Python.org:
Happy Pythoning! Mark as Completed Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Modules and Packages: An Introduction 🐍 Python Tricks 💌 Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team. Send Me Python Tricks » About John Sturtz John is an avid Pythonista and a member of the Real Python tutorial team. » More about JohnEach tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are: Dan Joanna Master Real-World Python Skills With Unlimited Access to Real Python Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » Master Real-World Python Skills Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » What Do You Think? Rate this article: Tweet Share Share EmailWhat’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know. Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. and get answers to common questions in our support portal. Apa itu package pada python?Secara umum, packages bisa diartikan sebagai sekumpulan modul atau file Python yang ditulis dengan (.py). Adapun isi dari modul tersebut terdiri dari kumpulan fungsi, class, variabel, maupun kode-kode Python lainnya.
Apa yang dimaksud dengan modul dan package?Modul adalah sebuah file yang berisikan sekumpulan kode fungsi dan global variabel yang disimpan dalam ekstensi .py . Sedangkan Package adalah sekumpulan modul yang memiliki constructur _init_ dalam satu folder.
Apa saja Library pada python?5 Rekomendasi Library Python yang Paling Populer Digunakan. Pandas.. NumPy.. TensorFlow.. SciPy.. 4.SciKit- Learn.. Plotly.. Apa itu import di python?Pada tutorial kali ini kita akan membahas tentang Mengenal Fungsi Import Pada Pemrograman Python, pada python import berfungsi untuk multi file maksudnya yaitu kita dapat memanggil file lain di dalam satu module yang berbeda.
|