• No results found

Module Built-In Functions

In document Making Use of Python (Page 152-156)

Some built-in functions can be used in functional programming. We will describe some of them in this section.

dir( )

The dir() built-in function returns a sorted list of strings containing the names defined by a module. The list contains the names of all the modules, variables, and functions that are defined in a module. For example, you can import the built-in mod- ule math and the module fib defined earlier. You can also use the dir() function to determine the names defined by these modules. Let’s see how this is done:

>>> import math, fib >>> dir(math)

[‘__doc__’, ‘__name__’, ‘acos’, ‘asin’, ‘atan’, ‘atan2’, ‘ceil’, ‘cos’, ‘cosh’, ‘e’, ‘exp’, ‘fabs’, ‘floor’, ‘fmod’, ‘frexp’, ‘hypot’, ‘ldexp’, ‘log’, ‘log10’, ‘modf’, ‘pi’, ‘pow’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’]

>>>dir(fib)

If you do not supply any arguments to the dir() function, the dir() function lists the names you have defined currently.

>>> tup=(‘111’,’abc’,64) >>> str=’xyz’

>>> import math, fib >>> fibo=fib.fibonacci >>> dir()

[‘__builtin__’, ‘__builtins__’, ‘__doc__’, ‘__name__’, ‘fib’, ‘fibo’, ‘math’, ‘os’, ‘str’, ‘string’, ‘sys’, ‘tup’]

The dir() function does not return the names of functions and variables that are loaded automatically by the interpreter. A list of functions and variables defined in the built-in standard module __built-in__ can be displayed as follows:

>>>import ___builtin__ >>>dir(__builtin__)

[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’,

‘DeprecationWarning’, ‘EOFError’, ‘Ellipsis’, ‘EnvironmentError’, ‘Exception’, ‘FloatingPointError’, ‘IOError’, ‘ImportError’, ‘IndentationError’, ‘IndexError’, ‘KeyError’, ‘KeyboardInterrupt’, ‘LookupError’, ‘MemoryError’, ‘NameError’, ‘None’, ‘NotImplemented’, ‘NotImplementedError’, ‘OSError’, ‘OverflowError’, ‘OverflowWarning’, ‘RuntimeError’, ‘RuntimeWarning’, ‘StandardError’, ‘StopIteration’, ‘SyntaxError’, ‘SyntaxWarning’, ‘SystemError’, ‘SystemExit’, ‘TabError’, ‘TypeError’, ‘UnboundLocalError’, ‘UnicodeError’, ‘UserWarning’,

‘ValueError’, ‘Warning’, ‘ZeroDivisionError’, ‘__debug__’, ‘__doc__’, ‘__import__’, ‘__name__’, ‘abs’, ‘apply’, ‘buffer’, ‘callable’, ‘chr’, ‘classmethod’, ‘cmp’, ‘coerce’, ‘compile’, ‘complex’, ‘copyright’, ‘credits’, ‘delattr’, ‘dictionary’, ‘dir’, ‘divmod’, ‘eval’, ‘execfile’, ‘exit’, ‘file’, ‘filter’, ‘float’, ‘getattr’, ‘globals’, ‘hasattr’, ‘hash’, ‘help’, ‘hex’, ‘id’, ‘input’, ‘int’, ‘intern’, ‘isinstance’, ‘issubclass’, ‘iter’, ‘len’, ‘license’, ‘list’, ‘locals’, ‘long’, ‘map’, ‘max’, ‘min’, ‘object’, ‘oct’, ‘open’, ‘ord’, ‘pow’, ‘property’, ‘quit’, ‘range’, ‘raw_input’, ‘reduce’, ‘reload’, ‘repr’, ‘round’, ‘setattr’, ‘slice’, ‘staticmethod’, ‘str’, ‘super’, ‘tuple’, ‘type’, ‘unichr’, ‘unicode’, ‘vars’, ‘xrange’, ‘zip’]

globals()and locals()

The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called. If locals()is called from within a function, it will return all the names that can be accessed locally from that function. If globals() is called from within a function, it will return all the names that can be accessed globally from that function. The return type of both these functions is dictionary. Therefore, names can be extracted using the keys()function. Let’s discuss this with the help of two modules, mainmod.py and fib1.py.

# mainmod.py import fib1

print “globals for main module:”,globals().keys() print “locals for main module:”,locals().keys() fib1.fibonacci(20) # fib1.py def fibonacci(a,num1=0,num2=1): print num1 while num2<a: print num2 num2=num1+num2 num1=num2-num1

print “globals for fibonacci:”,globals().keys() print “locals for fibonacci:”,locals().keys()

When you run the script in mainmod.py, you obtain the following output:

globals for main module: [‘__builtins__’, ‘__name__’, ‘fib1’, ‘__doc__’] locals for main module: [‘__builtins__’, ‘__name__’, ‘fib1’, ‘__doc__’] 0 1 1 2 3 5 8 13

globals for fibonacci: [‘__builtins__’, ‘__name__’, ‘__file__’, ‘__doc__’, ‘fibonacci’]

locals for fibonacci: [‘a’, ‘num1’, ‘num2’]

Notice that both locals() and globals() return the same dictionary in the main module because all the names in the global namespace can be accessed locally as well. In other words, both global and local namespaces contain the same names in the main module.

reload()

You have learned that the code in the top-level portion of a module is executed only once when the module is imported. Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this:

reload(module_name)

module_nameis the name of the module you want to reload and not the string con- taining the module name. For example, if the module you want to reload is mymodule, then module_name should be named mymodule and not ‘mymodule’. In addition, reload()will load only the module that has been loaded fully and not by using the from-importstatement.

In the previous chapter, you learned how functions add simplicity and modularity to your code. In this chapter, you learned how modules can be used to provide further modularity to your code. After writing several modules for a project, however, you may need to organize them in a structure so that you can easily access the names in each module.

Packages

In Python, packages allow you to create a hierarchical file directory structure of modules by using dotted module names. For example, mymodule.mod1 stands for a module, mod1, in the package mymodule. You already know that the same function and vari- able names can be used in different modules. You use fully qualified names to address these functions and variables in the same module. Similarly, modules with the same names can exist in different packages and are referred with dotted module names. You can be certain that module names in multimodule packages will not conflict. The use of modules is a good practice to group related modules.

For example, a package can be created for handling a banking application. There are many different types of accounts, such as savings bank account, current account, and fixed deposit. You need to create modules that will create all these types of accounts. Then, you will create modules for different finances provided by the bank, such as cor- porate, personal, infrastructure, and project. In addition, you will write modules to perform services for the bank, such as advisory, custodial, ATM, and credit card. Like this, you can have an endless stream of modules to perform these operations. Here’s a simple package structure that you can create for the previous example:

Bank/ __init__.py Account/ __init__.py savingsbank.py current.py fixed.py Finance/ __init__.py personal.py corporate.py infrastructure.py project.py Services/ __init__.py advisory.py custodial.py atm.py creditcard.py

The __init__.py file is required so that the interpreter can treat such a directory as a package. This file contains the information about the modules and subpackages that exist in a package so that subpackages are not hidden unintentionally while

searching for the module search path. In the simplest case, __init__.py can be empty but it can also contain initializer code for the module.

The fixed.py module in the previous example can be imported using the following:

import Bank.Account.fixed

To invoke a function in fixed.py, use the full name of the module:

Bank.Account.fixed.interest(Principal,rate=.12,period=5)

An alternative way of importing the submodule is:

from Bank.Account import fixed

The function interest can be invoked using the following statement:

fixed.interest()

You can also import the function or any variable in the fixed module directly by using the from-import statement as follows:

from Bank.Account.fixed import interest

Then, you execute it directly as follows:

interest()

Now let’s identify the modules to be used for the problem statement in the begin- ning of the chapter to perform user validations.

In document Making Use of Python (Page 152-156)