Python Module and Tricks By albro
hive-169321ยท@albroยท
0.000 HBDPython Module and Tricks By albro
<center></center> <p>In implementing a real, medium or large project, there is a lot of code in our program. <strong>Modules in Python</strong> help us organize this code. Each module is a Python file that contains code. By importing these, we can use its codes in other files.</p> <p>Suppose we have written user login for a project. Now we want to implement exactly the same system for another project. That means we have to write similar codes and functions!</p> <p>The solution that comes to our mind is that we use the previous codes in the new files. I'm not saying this method is bad! But <strong>managing changes</strong> and <strong>organizing these codes</strong> becomes a bit difficult.</p> <p>With the help of modules in Python, in addition to being able to organize our code, we can use frequently used code in several projects. By organizing, I mean writing program codes in specific files and using these files in combination.</p> <p>In this post, I'll first tell you how to create a module in Python. Then I'll explain how to call and use the modules. Finally, where to use additional discussions such as these modules.</p> <p>Finally, I will discuss additional considerations, such as where to use these modules.</p> <h3>Creating a Python module</h3> <p>Until this post from the series of Python posts, I used to write the codes in a file with <code>.py</code> format. I run this file in the command line or IDEs according to my needs.</p> <p>Each <code>.py</code> file is a module in Python! That means I can call and use its codes in another file. Suppose I wrote the <code>greetings()</code> function to print a simple message in <code>myprint.py</code> file: </p> <pre><code>def greetings(name): print("Hello {name}, Welcome to Hive Blockchain!")</code></pre> <p>Now I have a module called <code>myprint</code> that I can use in other files. ๐</p> <p>Before we use the module, it is better to know what kind of code is included in the Python module? We can put almost any kind of code in modules!</p> <ul> <li><a href="https://peakd.com/hive-169321/@albro/python-function-and-tricks">Python functions</a> that we have defined ourselves.</li> <li>Various <a href="https://peakd.com/hive-169321/@albro/python-variable-and-constant-by-albro">variables</a> such as <a href="https://peakd.com/hive-169321/@albro/python-dictionary-and-tricks-by-albro">dictionary</a>, Python <a href="https://peakd.com/hive-169321/@albro/python-string-and-tricks-by-albro">string</a> or <a href="https://peakd.com/hive-169321/@albro/python-list-and-tricks-by-albro">list</a>s</li> <li>Even codes in the main scope of the module! (Of course, the executable code in the module may cause problems for us, which we will review in the final section.)</li> </ul> <h3>Import the Python module</h3> <p>Now we want to call this function in the <code>app.py</code> file which is next to <code>myprint.py</code>. For this, we must first import the module into the <code>app</code> file. Simply put, we tell Python that:</p> >Copy the codes of this module in the current file! Because we want to use them. <p>To use the module, we use the <code>import</code> statement in Python. We can use this statement in 3 different structures, which I will explain below.</p> <center></center> <p><strong><code>import</code> module statemet in Python</strong></p> <p>The general structure of this command is similar to the following:</p> <pre><code>import module1 [,module2 [,module3 ...]]</code></pre> <p>To use the <code>myprint</code> module, I write the following statement at the beginning of the <code>app.py</code> file: </p> <pre><code>import myprint</code></pre> <p>If we want to import several modules at the same time, we use a comma (<code>,</code>) between the names. For example, in the following statement, in addition to our own module, I have called 2 mathematical calculation modules and Python random functions:</p> <pre><code>import myprint, math, random</code></pre> <p>When we want to call the <code>greetings()</code> function in the <code>app</code> file, we must add the "<strong>module name</strong>" along with a dot (<code>.</code>) to the beginning of the function name. Something like the following:</p> <pre><code>import myprint<br /> myprint.greetings("albro")</code></pre> <p>For example, to generate a random number between 0 and 20, we can do the following:</p> <pre><code>import random<br /> rnd = random.randint(0, 20)</code></pre> <p><strong><code>from import</code> statement</strong></p> <p>I create a file called <code>utils.py</code> with the following codes.</p> <pre><code># utils.py def calc(x): return (x**2)*(x+1)<br /> class Person(): def __init__(self, name): self.name = name<br /> users = ['albro', 'xeldal', 'minnowbooster']</code></pre> <p>If we call this module in another file (eg <code>app.py</code>), we will have access to all its functions, classes and variables:</p> <pre><code># app.py import utils<br /> print( utils.calc(5) )<br /> p1 = utils.Person('grindle')<br /> utils.users.append('leo.voter')</code></pre> <p>Sometimes we don't need all the code in a module. For example, we just want to use the <code>calc()</code> function. Therefore, importing other codes is unnecessary and somewhat unprofessional!</p> <p>To call only one or more items from the module, the <code>from ... import ...</code> structure is used.</p> <pre><code># import single thing from madule from utils import calc<br /> # import multiple things from utils import calc, users</code></pre> <p>simply! ๐</p> <p>In this case, when we want to call the function or variable, there is no need to write the name of the module at the beginning of them. That is, I can use the imported function and list as follows:</p> <pre><code>from utils import calc, users<br /> print( calc(5) )</code></pre> <p>If we want to call all functions and variables in the module in this way, an asterisk (<code>*</code>) is used instead of naming all functions:</p> <pre><code>from utils import *</code></pre> <p>In this way, the whole module is included in the code and we don't need to write the module name to use the functions.</p> <p><strong>Import with rename in Python</strong></p> <p>Sometimes we need to change the name of a module or things we have imported from it. This issue can have two general reasons:</p> <ul> <li>Let's shorten its name or call it by any desired name.</li> <li>This module or its functions have the same name as our codes.</li> </ul> <p>To change the name of the module in Python, we use the <code>as</code> keyword when calling. This method is also known as "<strong>alias</strong>".</p> <pre><code>import random as rnd</code></pre> <p>In the code above, I have included the <code>random</code> module with the alias <code>rnd</code> in the code. From now on, we should use <code>rnd</code> instead of <code>random</code>:</p> <pre><code>rnd.randint(0, 20)</code></pre> <p>We can also use this for functions that are imported; Like the following code:</p> <pre><code>from utils import calc as calculate<br /> print( calculate(5) )</code></pre> <center></center> <p>At the beginning of the post, I briefly reviewed the use of modules with you. Personally, I consider 4 general uses for modules in Python:</p> <ol> <li>Organize code by converting a set of related functions into a module</li> <li>The possibility of reusing some code (and making our program modular)</li> <li>With the help of modularization, we can use other people's codes (or our own previous codes).</li> <li>We may publish or make these modules available to others.</li> </ol> <p><strong>Search path for python modules</strong></p> <p>When the <code>import</code> statement is used, the Python interpreter checks several paths to call the desired module. First, it searches in the list of built-in modules that exist with the <a href="https://peakd.com/hive-169321/@albro/install-python-on-windows-by-albro">installation of Python</a>, and if nothing is found, it looks for the desired module in other paths.</p> <p>In general, the following routes are checked in order:</p> <ul> <li>Built-in modules</li> <li>Current folder</li> <li>Folders that are in the operating system's local PYTHONPATH variable. (The one defined in the Python path setting.)</li> <li>Several folders in the Python installation path</li> </ul> <p><strong><code>dir</code> function to check the module</strong></p> <p>The <code>dir()</code> function takes the module we imported as input and gives us a list of functions and variables inside it. This function is usually used for module checking or Python error handling tasks.</p> <pre><code>import utils<br /> print( dir(utils) )<br /> # output: # ['Person', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'calc', 'users']</code></pre>
๐ bgmoha, pars.team, elector, goldfoot, botito, tobor, hadaly, dotmatrix, curabot, chomps, freysa, lunapark, weebo, otomo, quicktrade, buffybot, hypnobot, psybot, chatbot, psychobot, misery, freebot, cresus, honeybot, dtake, quicktrades, droida, meins0815, crimo, pibara, taradraz1, chessbrotherspro, vjap55, samostically, cyprianj, eniolw, misterlangdon, eumorrell, rosmarly, oabreuf24, fernandoylet, nazom, raca75, philipp87, frankrey11, jrevilla, adrianalara, lk666, emrysjobber, hivebuzz, lizanomadsoul, jnmarteau, steemitboard, marivic10, arcange, shainemata, laruche, aweee, michupa, achimmertens, rohansuares, walterjay, robotics101, pboulet, louis00334, jasonbu, roozeec, ydaiznfts, aioflureedb, lemouth, steemstem-trig, steemstem, dna-replication, minnowbooster, howo, aboutcoolscience, stemsocial, metabs, techslut, dhimmel, helo, alexander.alexis, tsoldovieri, fragmentarion, alexdory, charitybot, melvin7, zeruxanime, lamouthe, curie, edb, samminator, postpromoter, madridbg, sco, deholt, nattybongo, gerdtrudroepke, stem.witness, crowdwitness, apokruphos, plicc8, valth, oluwatobiloba, mobbs, sustainablyyours, kenadis, r00sj3, intrepidphotos, geopolis, francostem, gadrian, de-stem, charitymemes, noelyss, greengalletti, pinkfloyd878, kqaosphreak, abigail-dantes, aidefr, bhoa, emiliomoron, temitayo-pelumi, doctor-cog-diss, cubapl, seinkalar, enzor, pandasquad, croctopus, satren, cnfund, joeyarnoldvn, fotogruppemunich, studio666, kggymlife, dcrops, justyy, t-nil, stayoutoftherz, fineartnow, kgswallet, cheese4ead, steemstorage, quinnertronics, hiveonboard, cloh76, meritocracy, zyx066, therising, armandosodano, aicu, therealwolf, takowi, traderhive, the-burn, rt395, irgendwo, yixn, smartsteem, tobias-g, sunsea, dragibusss, humbe, musicvoter2, thelittlebank, roamingsparrow, the-grandmaster, meno, ahmadmangazap, tinyhousecryptos, sarashew, tfeldman, photohunt, gaottantacinque, arunava, cribbio, steemean, aabcent, gasaeightyfive, bitrocker2020, gunthertopp, thelordsharvest, punchline, empath, baltai, aries90, steemwizards, enjar, movingman, bflanagin, iansart, superlotto, greddyforce, revo, braaiboy, princessmewmew, citizendog, steemcryptosicko, monica-ene, sunshine, utube, steveconnor, brianoflondon, investingpennies, qberry, diabonua, podping, communitybank, sportscontest, fantasycrypto, talentclub, cleanplanet, metroair, neumannsalva, tanzil2024, trenz, oscarina, cleanyourcity, juancar347, cliffagreen, jacuzzi, qwerrie, sbtofficial, kylealex, federacion45, dynamicrypto, detlev, neneandy, cryptofiloz, xeldal, mcsvi, firstamendment, adol, enki, ibt-survival, tomiscurious, fatman, votehero, voter003, xxeldal, elevator09, sanderjansenart, mafufuma, hiddendragon, robibasa, potsuperiya, carilinger, pladozero, atheistrepublic, dondido, lightpaintershub, sandymeyer, lordvader, jerrybanfield, cryptictruth, juecoree, stem-espanol, lorenzor, ufv, iamphysical, sandracarrascal, ydavgonzalez, delpilar, elvigia, josedelacruz, erickyoussif, uche-nna, reinaseq, aleestra, giulyfarci52, hyun-soo, analealsuarez, azulear, miguelangel2801, tomastonyperez, andrick, fran.frey, aqua.nano, newton666, psicoluigi, chrislybear, mammasitta, massivevibration, dandays, vaultec, nfttunz, eric-boucher, robertbira, eliaschess333, nicole-st, imcore, ajfernandez, amansharma555, flatman, holoferncro, ennyta, endopediatria, aotearoa, celf.magazine, josemalavem, rogmy, votomasivo, vezo, fulani, yohanys, librepensadora, tomasjurado, healjoal, crisch23, camiloferrua, dmercadoelis, eleazarvo, jessescenica, nafonticer, violetaperez, pepiflowers, bateristasvzla, carl3, lphnfotografia, davidcurrele, kattycrochet, stea90, alejandrobons, bluefinstudios, gamersclassified, chainableit, roelandp,