PYTHON PACKAGES
Yahoo Answers to Shut Down Permanently in Ma
When you've got a large number of Python classes (or "modules"), you'll want to organize them into packages. When the number of modules (simply stated, a module might be just a file containing some classes) in any project grows significantly, it is wiser to organize them into packages – that is, placing functionally similar modules/classes in the same directory. This article will show you how to create a Python package.
Working with Python packages is really simple. All you need to do is:
Create a directory and give it your package's name.
Put your classes in it.
Create a __init__.py file in the directory
That's all! In order to create a Python package, it is very easy. The __init__.py file is necessary because with this file, Python will know that this directory is a Python package directory other than an ordinary directory (or folder – whatever you want to call it). Anyway, it is in this file where we'll write some import statements to import classes from our brand new package.
In this tutorial, we will create an Animals package – which simply contains two module files named Mammals and Birds, containing the Mammals and Birds classes, respectively.
So, first we create a directory named Animals.
Now, we create the two classes for our package. First, create a file named Mammals.py inside the Animals directory and put the following code in it:
class Mammals:
def __init__(self):
''' Constructor for this class. '''
# Create some member animals
self.members = ['Tiger', 'Elephant', 'Wild Cat']
def printMembers(self):
print('Printing members of the Mammals class')
for member in self.members:
print('\t%s ' % member)
The code is pretty much self-explanatory! The class has a property named members – which is a list of some mammals we might be interested in. It also has a method named printMembers which simply prints the list of mammals of this class! Remember, when you create a Python package, all classes must be capable of being imported, and won't be executed directly.
Next we create another class named Birds. Create a file named Birds.py inside the Animals directory and put the following code in it:
class Birds:
def __init__(self):
''' Constructor for this class. '''
# Create some member animals
self.members = ['Sparrow', 'Robin', 'Duck']
def printMembers(self):
print('Printing members of the Birds class')
for member in self.members:
print('\t%s ' % member)
This code is similar to the code we presented for the Mammals class.
Finally, we create a file named __init__.py inside the Animals directory and put the following code
from Mammals import Mammals
from Birds import Birds
That's it! That's all there is to it when you create a Python package. For testing, we create a simple file named test.py in the same directory where the Animals directory is located. We place the following code in the test.py file:
# Import classes from your brand new package
from Animals import Mammals
from Animals import Birds
# Create an object of Mammals class & call a method of it
myMammal = Mammals()
myMammal.printMembers()
# Create an object of Birds class & call a method of it
myBird = Birds()
myBird.printMembers()
PYTHON PIP
PIP is a package manager for Python packages, or modules if you like.
Note: If you have Python version 3.4 or later, PIP is included by default.
A package contains all the files you need for a module.
Modules are Python code libraries you can include in your project.
Navigate your command line to the location of Python's script directory, and type the following:
Check PIP version:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip --version
If you do not have PIP installed, you can download and install it from this page: https://pypi.org/project/pip/
Downloading a package is very easy.
Open the command line interface and tell PIP to download the package you want.
Navigate your command line to the location of Python's script directory, and type the following:
Download a package named "camelcase":
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip install camelcase
Now you have downloaded and installed your first package!
Once the package is installed, it is ready to use.
Import the "camelcase" package into your project.
Import and use "camelcase":
import camelcase
c = camelcase.CamelCase()
txt = "hello world"
print(c.hump(txt))
Find more packages at https://pypi.org/.
Use the uninstall command to remove a package:
Uninstall the package named "camelcase":
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip uninstall camelcase
The PIP Package Manager will ask you to confirm that you want to remove the camelcase package:
Uninstalling camelcase-02.1:
Would remove:
c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase-0.2-py3.6.egg-info
c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase\*
Proceed (y/n)?
Press y and the package will be removed.
Use the list command to list all the packages installed on your system:
List installed packages:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip list
Result:
Package Version
-----------------------
camelcase 0.2
mysql-connector 2.1.6
pip 18.1
pymongo 3.6.1
setuptools 39.0.1
PYTHON MODULES
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
To create a module just save the code you want in a file with the file extension .py:
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Now we can use the module we just created, by using the import statement:
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Note: When using a function from a module, use the syntax: module_name.function_name.
The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
You can name the module file whatever you like, but it must have the file extension .py
You can create an alias when you import a module, by using the as keyword:
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
There are several built-in modules in Python, which you can import whenever you like.
Import and use the platform module:
import platform
x = platform.system()
print(x)
There is a built-in function to list all the function names (or variable names) in a module. The dir() function:
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create yourself.
You can choose to import only parts from a module, by using the from keyword.
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])
DATE MODULE
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x)
When we execute the code from the example above the result will be:
2021-04-11 13:42:37.584738
The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date object.
Here are a few examples, you will learn more about them later in this chapter:
Return the year and name of weekday:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
To create a date, we can use the datetime() class (constructor) of the datetime module.
The datetime() class requires three parameters to create a date: year, month, day.
Create a date object:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and has a default value of 0, (None for timezone).
The datetime object has a method for formatting date objects into readable strings.
The method is called strftime(), and takes one parameter, format, to specify the format of the returned string:
Display the name of the month:
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
MATH MODULE
Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.
The min() and max() functions can be used to find the lowest or highest value in an iterable:
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
The abs() function returns the absolute (positive) value of the specified number:
x = abs(-7.25)
print(x)
The pow(x, y) function returns the value of x to the power of y (xy).
Return the value of 4 to the power of 3 (same as 4 * 4 * 4):
x = pow(4, 3)
print(x)
Python has also a built-in module called math, which extends the list of mathematical functions.
To use it, you must import the math module:
import math
When you have imported the math module, you can start using methods and constants of the module.
The math.sqrt() method for example, returns the square root of a number:
import math
x = math.sqrt(64)
print(x)
The math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method rounds a number downwards to its nearest integer, and returns the result:
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
The math.pi constant, returns the value of PI (3.14...):
import math
x = math.pi
print(x)
JSON MODULE
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
Python has a built-in package called json, which can be used to work with JSON data.
Import the json module:
import json
If you have a JSON string, you can parse it by using the json.loads() method.
The result will be a Python dictionary.
Convert from JSON to Python:
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
Convert from Python to JSON:
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
You can convert Python objects of the following types, into JSON strings:
dict
list
tuple
string
int
float
True
False
None
Convert Python objects into JSON strings, and print the values:
import json
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
Convert a Python object containing all the legal data types:
import json
x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))
The example above prints a JSON string, but it is not very easy to read, with no indentations and line breaks.
The json.dumps() method has parameters to make it easier to read the result:
Use the indent parameter to define the numbers of indents:
json.dumps(x, indent=4)
You can also define the separators, default value is (", ", ": "), which means using a comma and a space to separate each object, and a colon and a space to separate keys from values:
Use the separators parameter to change the default separator:
json.dumps(x, indent=4, separators=(". ", " = "))
The json.dumps() method has parameters to order the keys in the result:
Use the sort_keys parameter to specify if the result should be sorted or not:
json.dumps(x, indent=4, sort_keys=True)
REGEX MODULE
A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
RegEx can be used to check if a string contains the specified search pattern.
Python has a built-in package called re, which can be used to work with Regular Expressions.
Import the re module:
import re
When you have imported the re module, you can start using regular expressions:
Search the string to see if it starts with "The" and ends with "Spain":
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
The re module offers a set of functions that allows us to search a string for a match:
Function
Description
Returns a list containing all matches
Returns a Match object if there is a match anywhere in the string
Returns a list where the string has been split at each match
Replaces one or many matches with a string