01. Importing modules
The strength of Python is its ability to be extended through modules. The first step in many programs is to import those modules that you need.The simplest import statement is to just call ‘import modulename’. In this case, those functions and objects provided are not in the general namespace.
You need to call them using the complete name (modulename.methodname). You can shorten the ‘modulename’ part with the command ‘import modulename as mn’. You can skip this issue completely with the command ‘from modulename import’ to import everything from the given module.Then you can call those provided capabilities directly.If you only need a few of the provided items, you can import them selectively by replacing the ‘’ with the method or object names.
02. Reloading modules
When a module is first imported, any initialization functions are run at that time. This may involve creating data objects, or initiating connections. But, this is only done the first time within a given session.
Importing the same module again won’t re-execute any of the initialization code. If you want to have this code re-run, you need to use the reload command. The format is ‘reload(modulename)’. Something to keep in mind is that the dictionary from the previous import isn’t dumped, but only written over. This means that any definitions that have changed between the import and the reload are updated correctly. But if you delete a definition, the old one will stick around and still be accessible. There may be other side effects, so always use with caution.
03. Installing new modules
While most of the commands we are looking at are Python commands that are to be executed within a Python session, there are a few essential commands that need to be executed outside of Python. The first of these is pip.
Installing a module involves downloading the source code, and compiling any included external code. Luckily, there is a repository of hundreds of Python modules available at http://pypi.python.org. Instead of doing everything manually, you can install a new module by using the command ‘pip install module name’. This command will also do a dependency check and install any missing modules before installing the one you requested.
You may need administrator rights if you want this new module installed in the global library for your computer. On a Linux machine, you would simply run the pip command with sudo. Otherwise, you can install it to your personal library directory by adding the command line option ‘—user’
04. Executing a script
Importing a module does run the code within the module fi le, but does it through the module maintenance code within the Python engine. This maintenance code also deals with running initializing code. If you only wish to take a Python script and execute the raw code within the current session, you can use the ‘execfile(“filename.py”)’ command, where the main option is a string containing the Python file to load and execute.
By default, any definitions are loaded into the locals and globals of the current session. You can optionally include two extra parameters the execfile command.
These two options are both dictionaries, one for a different set of locals and a different set of globals. If you only hand in one dictionary, it is assumed to be a globals dictionary. The return value of this command is None.
05. An enhanced shell
The default interactive shell is provided through the command ‘python’, but is rather limited. An enhanced shell is provided by the command ‘ipython’. It provides a lot of extra functionality to the code developer. A thorough history system is available, giving you access to not only commands from the current session, but also from previous sessions. There are also magic commands that provide enhanced ways of interacting with the current Python session. For more complex interactions, you can create and use macros. You can also easily peek into the memory of the Python session and decompile Python code. You can even create profiles that allow you to handle initialization steps that you may need to do every time you use iPython.
06. Evaluating code
Sometimes, you may have chunks of code that are put together programmatically. If these pieces of code are put together as a string, you can execute the result with the command ‘eval(“code_string”)’. Any syntax errors within the code string are reported as exceptions. By default, this code is executed within the current session, using the current globals and locals dictionaries.
The ‘eval’ command can also take two other optional parameters, where you can provide a different set of dictionaries for the globals and locals. If there is only one additional parameter, then it is assumed to be a globals dictionary. You can optionally hand in a code object that is created with the compile command instead of the code string. The return value of this command is None.
07. Asserting values
At some point, we all need to debug some piece of code we are trying to write. One of the tools useful in this is the concept of an assertion. The assert command takes a Python expression and checks to see if it is true. If so, then execution continues as normal. If it is not true, then an Assertion Error is raised. This way, you can check to make sure that invariant within your code stay invariant.
By doing so, you can check assumptions made within your code. You can optionally include a second parameter to the assert command. This second parameter is Python expression that is executed if the assertion fails. Usually, this is some type of detailed error message that gets printed out. Or, you may want to include cleanup code that tries to recover from the failed assertion.
08. Mapping functions
A common task that is done in modern programs is to map a given computation to an entire list of elements. Python provides the command ‘map()’ to do just this. Map returns a list of the results of the function applied to each element of an iterable object. Map can actually take more than one function and more than one iterable object.
If it is given more than one function, then a list of tuples is returned, with each element of the tuple containing the results from each function. If there is more than one iterable handed in, then map assumes that the functions take more than one input parameter, so it will take them from the given iterables. This has the implicit assumption that the iterables are all of the same size, and that they are all necessary as parameters for the given function.
09. Virtualenvs
Because of the potential complexity of the Python environment, it is sometimes best to set up a clean environment within which to install only the modules you need for a given project. In this case, you can use the virtualenv command to initialize such an environment. If you create a directory named ‘ENV’, you can create a new environment with the command ‘virtualenv ENV’. This will create the sub directories bin, lib and include, and populate them with an initial environment. You can then start using this new environment by sourcing the script ‘ENV/bin/activate’, which will change several environment variables, such as the PATH.
When you are done, you can source the script ‘ENV/bin/deactivate’ to reset your shell’s environment back to its previous condition. In this way, you can have environments that only have the modules you need for a given set of tasks.
10. Loops
While not strictly commands, everyone needs to know how to deal with loops. The two main types of loops are a fixed number of iterations loop (for) and a conditional loop (while). In a for loop, you iterate over some sequence of values, pulling them off the list one at a time and putting them in a temporary variable. You continue until either you have processed every element or you have hit a break command. In a while loop, you continue going through the loop as long as some test expression evaluates to True.
While loops can also be exited early by using the break command, you can also skip pieces of code within either loop by using a continue command to selectively stop this current iteration and move on to the next one.
Posted on Utopian.io - Rewarding Open Source Contributors
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Thanks Sir.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Hey @holudghuri I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Thanks For your Support @utopian-io
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit