Modules Flashcards
Write a code that will import a specific function add_numbers
from a library adding_library
?
import add_numbers from adding_library
What are Python Modules?
At its core, a module is just a Python file with code in it. You can import entire files or specific functions from those files for use in other applications.
How to create and use modules?
- Simply write the code you want and save it in a .py file.
- You can then use import to access functions in that file from other files by using the syntax from import
from <filename without the .py extension> import <function name>
What is a possible complication from importing a lot of code?
Name Dublication
* Importing code further complicates things because you will be importing names into your code that maybe you would have wanted to use yourself.
Explain Namespace
- System to help make the names of functions and variables unique
- Prevent duplication across modules and packages.
Python namespaces include the following:
- built-in namespace: contains all built-in functions and exceptions.
-
global namespace: contains all the names of variables and functions you create in your program that exist outside of functions
* local namespace: contains only names within a given function.
Importing the floor function form the maths module, in which namespace would it be?
- Global Namespace
How to avoid duplicate names?
- By importing entire library
- Variables and functions in library are now accessed with dot notation
- Now: having exported variable in own global namespace, thus eliminating conflict with library function of the same name
import math math.floor(6.5)
There is a function, my_function. Within that function, a variable called my_var is created. In which namespace does my_var exist?
- Local
Python’s int( ) function will take an argument and convert it to an integer. In which namespace does int( ) exist?
Build-In
How to improve documentation
- Properly named functions
- Informative comments
What is a docstring and how to use it. Give example
def add_two_numbers(a, b): """ Adds two numbers together and returns the result. """
Or over various Lines
""" text tect text """
Accessed like this
help(add_two_numbers)