{"id":137,"date":"2017-07-07T21:34:32","date_gmt":"2017-07-07T21:34:32","guid":{"rendered":"https:\/\/xiaohaionline.com\/?p=137"},"modified":"2017-07-08T01:45:32","modified_gmt":"2017-07-08T01:45:32","slug":"understanding-the-python-world","status":"publish","type":"post","link":"https:\/\/xiaohaionline.com\/index.php\/2017\/07\/07\/understanding-the-python-world\/","title":{"rendered":"Understanding the Python world"},"content":{"rendered":"<p>There are two classes of Python users, those who use Python for management scripting and web development, and those who use Python for scientific computing. According to many, Python is winning the war against R in the field of machine learning. As machine learning becomes ever more important and popular, so is Python.<\/p>\n<p>This article is for those just got into the Python world. For those experienced Python developers, you are excused to leave now. Python is extremely simple to start with, the traditional <em>Hello World<\/em> program takes only one line. Before no time, you would be writing classes, methods, system calls, and you really enjoy the convenience and power of the language. But quickly, you also realize that, there are many strange codes floating around. And you hear about lots of unacquainted jargons. You could feel a little puzzled, and a little confused about the big picture of the Python world.<\/p>\n<p>That is where this article comes to help. I intend to draw a broad picture of the Python world, with pointers for you to explore in depth. At the end of the article, you won&#8217;t become an expert on anything with Python. But, hopefully, you will be satisfied in understanding the big picture, and know where to go for further information and to gain expertise.<br \/>\n<!--more--><\/p>\n<h3>Installation and environments<\/h3>\n<p>All software packages start with installations. As of the writing of this post, there are two major versions of Python that are prevalent, i.e. <a href=\"https:\/\/docs.python.org\/2\/index.html\">Python 2<\/a> and <a href=\"https:\/\/docs.python.org\/3.5\/\">Python 3<\/a>. Usually, <a href=\"https:\/\/docs.python.org\/2\/index.html\">Python 2<\/a> refers to Python with version 2.7.x, and <a href=\"https:\/\/docs.python.org\/3.5\/\">Python 3<\/a> refers to Python with version 3.5+. Python 2 and Python 3 are <a href=\"https:\/\/wiki.python.org\/moin\/Python2orPython3\">incompatible<\/a> on many occasions. Which one to choose? The simplified answer is to choose Python 3 for new projects and use whatever version your old project was using for the old projects.<\/p>\n<p>Chances are, in the near future, you will need to work in both Python 2 and Python 3 worlds for different projects. So you install both. But then, how do you switch between the two? When you run <em>python -m xxx<\/em> command, how do you know which version is started? Do you need to manually set up your environment variables for switching? That would be too complicated and error prone, and you need tools. That is when <a href=\"https:\/\/virtualenv.pypa.io\/en\/stable\/\">Virtualenv<\/a> and <a href=\"https:\/\/www.continuum.io\/\">Anaconda<\/a> come into play.<\/p>\n<p><a href=\"https:\/\/virtualenv.pypa.io\/en\/stable\/\">Virtualenv<\/a> and <a href=\"https:\/\/www.continuum.io\/\">Anaconda<\/a> solve more problems than Python versions. Remember, for any real projects, you would need support from many libraries, right? Different projects usually rely on different versions of the same libraries, i.e. it is incorrect to assume all of your projects can always use the latest version of the same libraries. For different projects could be at different lifecycles. So the industry&#8217;s best practice is to isolate <em>the python version + specific libraries versions<\/em> into one bundle called: <strong><em>environments<\/em><\/strong>.<\/p>\n<p>The difference between <a href=\"https:\/\/virtualenv.pypa.io\/en\/stable\/\">Virtualenv<\/a> and <a href=\"https:\/\/www.continuum.io\/\">Anaconda<\/a>? Again, the simplest answer is<\/p>\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">Anaconda = Virtualenv + Pip<\/div><\/div>\n<p>functionality wise. Wait, what is Pip? Be patient, I will talk about it. But before that, I&#8217;d like to show some codes:<\/p>\n<p>On MacOS, with Virtualenv, commands to install and setup both Python 2 &amp; 3 environments are:<\/p>\n<pre>\n\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">brew install python<br \/>\nbrew install python3<br \/>\nvirtualenv env2<br \/>\nvirtualenv --python=python3 env3<\/div><\/div>\n\n<\/pre>\n<p>In the above codes, env2 and env3 and simply subfolders (that you can change to your favorite folder names) where the environments will be setup, i.e. all python binaries and libraries will be install and copied into those subfolders.<\/p>\n<p>Environments need to be activated before invoking Python commands:<\/p>\n<pre>\n\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">source env2\/bin\/activate<br \/>\ndeactivate<br \/>\nsource env3\/bin\/activate<br \/>\ndeactivate<\/div><\/div>\n\n<\/pre>\n<p>For Anaconda:<\/p>\n<pre>\n\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">conda create --prefix ~\/bio-env python=3.4<br \/>\nsource activate ~\/bio-env<br \/>\nsource deactivate<\/div><\/div>\n\n<\/pre>\n<p>In the above codes, you can change to the Python version to use Python 2.<\/p>\n<h3>Package installer<\/h3>\n<p>As promised, I will talk about <a href=\"https:\/\/pip.pypa.io\/en\/stable\/\">Pip<\/a>. As you would expect, any programmer needs libraries. In Python, libraries are called packages. Like in Java world, you pull and install packages from some central repositories called <a href=\"https:\/\/pypi.python.org\/pypi\">PyPI &#8211; the Python Package Index<\/a>. Most likely you don&#8217;t have to install <a href=\"https:\/\/pip.pypa.io\/en\/stable\/\">Pip<\/a>. For <a href=\"https:\/\/pip.pypa.io\/en\/stable\/\">Pip<\/a> is installed when you install your Python environments.<\/p>\n<p>Some sample pip commands for installing packages:<\/p>\n<pre>\n\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">pip install SomePackage &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# latest version<br \/>\npip install SomePackage==1.0.4 &nbsp; &nbsp; # specific version<br \/>\npip install 'SomePackage&amp;gt;=1.0.4' &nbsp; &nbsp; # minimum version<br \/>\npip install -r requirements.txt . # &quot;Requirements files&quot; are files containing a list of items to be installed<br \/>\npip list # list installed packages<br \/>\npip search &quot;query&quot; # search for packages<br \/>\npip install --upgrade SomePackage # upgrade packages if needed<\/div><\/div>\n\n<\/pre>\n<p>Another concept you need to understand is <a href=\"http:\/\/pythonwheels.com\/\">Python Wheels<\/a>.<\/p>\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">Pip install<\/div><\/div>\n<p>, by default, installs from source files involving compilation. This process could be demanding at times, especially when non-python libraries are involved. So the invention of the <a href=\"http:\/\/pythonwheels.com\/\">Python Wheels<\/a> is to allow others to pre-built a package for you, so that you can quickly install without worrying about how to compile the package. Make sense, right?<\/p>\n<pre>\n\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">pip install SomePackage-1.0-py2.py3-none-any.whl # installing from wheels<br \/>\npip install wheel<br \/>\npip wheel --wheel-dir=\/local\/wheels -r requirements.txt # To build wheels to a local directory<\/div><\/div>\n\n<\/pre>\n<p>Remember <a href=\"https:\/\/www.continuum.io\/\">Anaconda<\/a>? It gets its own package installer tool. It is called <a href=\"https:\/\/conda.io\/docs\/intro.html\">Conda<\/a>. Its usage patttern is similar to pip, but using a different central repository, the one from <a href=\"http:\/\/repo.continuum.io\/pkgs\/\">Continnum<\/a>.<\/p>\n<pre>\n\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">conda create --name snakes python=3 # create python 3 environment called snakes<br \/>\nconda info --envs # display the list of environments<br \/>\nsource activate snowflakes # activate snowflakes environment<br \/>\nconda search beautiful-soup # search packages<br \/>\nconda install package_name # install a package<br \/>\nconda list # list installed packages<br \/>\nconda update package_name # update a package<br \/>\nconda update conda # update conda itself<br \/>\nconda update python # update to the latest 2.x or 3.x version of python<br \/>\nconda remove packge_name # uninstall a package<\/div><\/div>\n\n<\/pre>\n<p>In addition to the central repository, Anaconda also supports &#8220;private&#8221; repositories hosted on <a href=\"https:\/\/anaconda.org\/\">anaconda.org<\/a>. The &#8220;private&#8221; repositories are called <a href=\"https:\/\/conda.io\/docs\/custom-channels.html\">channels<\/a>. In install from a <a href=\"https:\/\/conda.io\/docs\/custom-channels.html\">channel<\/a>, you can use the -c option, e.g.<\/p>\n<pre>\n\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">conda install -c pandas bottleneck<\/div><\/div>\n\n<\/pre>\n<p>Don&#8217;t worry, with Anaconda, you can still use Pip.<\/p>\n<p>I personally prefer Anaconda because it has more integrated support cross platforms and it has enough packages for scientific computing.<\/p>\n<h3>Your own modules and packages<\/h3>\n<p>With the installation and environments taken care of, you are ready to do some serious coding.<\/p>\n<p>You write a python file with the .py as the extension. Congratulations, you&#8217;ve got your first <a href=\"https:\/\/docs.python.org\/2\/tutorial\/modules.html\">module<\/a> developed. Of course, you will want to write your own libraries for others to use. Well it is quite somple:<\/p>\n<ol>\n<li>Create a folder named after your library name<\/li>\n<li>Within that folder, put an empty __init__.py in it<\/li>\n<\/ol>\n<p>Congratulations, you got your first package ready. Of course, it has no meat in it. For you have not done any real coding.<\/p>\n<p>If you want some classes visible to others when they write<\/p>\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">import your_package_name<\/div><\/div>\n<p>, you define the class in the __init__.py object. If you prefer other to write<\/p>\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">import your_package_name.your_module<\/div><\/div>\n<p>or<\/p>\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">from your_package_name import your_module<\/div><\/div>\n<p>, you keep the __init__.py empty and create<\/p>\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">your_module.py<\/div><\/div>\n<p>.<\/p>\n<p>Don&#8217;t expect me to talk about how to write Python classes. It should be another of your Google searches.<\/p>\n<h3>Install your own packages<\/h3>\n<p>Time to share your work with others. Visit <a href=\"https:\/\/packaging.python.org\/tutorials\/distributing-packages\/\">this<\/a> page to equip yourself with the full knowledge. Basically you need to provide a set of meta information to inform the packager how to package your stuff. Briefly:<\/p>\n<ul>\n<li>setup.py &#8211; this is your main file containing a call of setup() from <a href=\"https:\/\/pypi.python.org\/pypi\/setuptools\">Setuptools<\/a> package indicating package name and url etc.<\/li>\n<li>setup.cfg &#8211; an ini file that contains option defaults for setup.py commands<\/li>\n<li>MANIFEST.in &#8211; needed in certain cases where you need to package additional files such as resource files<\/li>\n<li>optional stuff &#8211; license file, author file, contributions file etc<\/li>\n<\/ul>\n<p>The following commands will help you to have a sense how to package.<\/p>\n<pre>\n\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">python setup.py sdist # create a source distribution<br \/>\npython setup.py bdist_wheel --universal # a universal (meaning pure python) wheel<\/div><\/div>\n\n<\/pre>\n<p>If you need to upload your package into the <a href=\"https:\/\/pypi.python.org\/pypi\">PyPi repository<\/a> to have a broader audience, you further need the <a href=\"https:\/\/pypi.python.org\/pypi\/twine\">twine<\/a> tool.<\/p>\n<h3>Deploy your packages<\/h3>\n<p>For any serious project, you would need to deploy it to some servers and get it running. The <a href=\"http:\/\/www.fabfile.org\/installing.html\">Fabric package<\/a> is here to make it easy. Python <a href=\"http:\/\/www.fabfile.org\/\">Fabric<\/a> allows you to easily invoke shell scripts locally or remotely on the servers.<\/p>\n<p>At the top of your project folder, you want to create a<\/p>\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">fabfile.py<\/div><\/div>\n<p>which contains your deployment scripts. Some important imports at the top of that script:<\/p>\n<pre>\n\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">from fabric.api import task, local, settings<br \/>\nfrom fabric.colors import green, red<br \/>\nfrom fabric.context_managers import prefix<\/div><\/div>\n\n<\/pre>\n<p>Each method you define in the<\/p>\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">fabfile.py<\/div><\/div>\n<p>becomes a subcommand as the<\/p>\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">fab<\/div><\/div>\n<p>. For example, the following routine:<\/p>\n<pre>\n\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">@task<br \/>\ndef mytask():<br \/>\n&amp;nbsp;&amp;nbsp;run(&quot;a command&quot;)<\/div><\/div>\n\n<\/pre>\n<p>Sould allow you to invoke command from within the top folder of your project:<\/p>\n<pre>\n\n<div class=\"codecolorer-container text default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"text codecolorer\">fab mytask<\/div><\/div>\n\n<\/pre>\n<p>It is generally a good practice to have separate tasks for bootstrapping, deployment and testing. A tutorial is available <a href=\"http:\/\/docs.fabfile.org\/en\/1.13\/tutorial.html\">here<\/a>.<\/p>\n<h3>Python unit testing<\/h3>\n<p>We should never forget about tests whenever we are coding, right? <a href=\"https:\/\/docs.pytest.org\/en\/latest\/\">Pytest<\/a> is the tool to use for that purpose.<\/p>\n<h3>Welcome to REST<\/h3>\n<p>Here the REST means <a href=\"https:\/\/en.wikipedia.org\/wiki\/Representational_state_transfer\">Representational state transfer<\/a>. We often need to deliver a micro service out of Python. Then <a href=\"http:\/\/flask.pocoo.org\/\">Flask<\/a> is a good choice for that. It is RESTful, it supports templating and it is fully <a href=\"http:\/\/www.python.org\/dev\/peps\/pep-0333\/\">WSGI<\/a> compliant.<\/p>\n<h3>Expand your horizon<\/h3>\n<ul>\n<li><strong>IPython<\/strong> &#8211; I just can\u2019t stress enough how useful this tool is. It is a python prompt on steroids. It has completion, history, shell capabilities, and a lot more. Make sure that you take a look at it.<\/li>\n<li><strong>NumPy<\/strong> &#8211; You do math or science? You can not live without it.<\/li>\n<li><strong>SciPy<\/strong> &#8211; When we talk about NumPy then we have to talk about scipy. It is a library of algorithms and mathematical tools for python and has caused many scientists to switch from ruby to python.<\/li>\n<li><strong>matplotlib<\/strong> &#8211; A numerical plotting library. It is very useful for any data scientist or any data analyzer.<\/li>\n<li><strong>SymPy<\/strong> &#8211; SymPy can do algebraic evaluation, differentiation, expansion, complex numbers, etc. It is contained in a pure Python distribution.<\/li>\n<li><strong>NLTK<\/strong> &#8211; Natural Language Toolkit \u2013 I realize most people won\u2019t be using this one, but it\u2019s generic enough. It is a very useful library if you want to manipulate strings. But it\u2019s capacity is beyond that. Do check it out.<\/li>\n<li><strong>SQLAlchemy<\/strong> &#8211; A database library. Many love it and many hate it. The choice is yours.<\/li>\n<li><strong>BeautifulSoup<\/strong> &#8211; I know it\u2019s slow but this xml and html parsing library is very useful for beginners.<\/li>\n<li><strong>Requests<\/strong> &#8211; The most famous http library written by kenneth reitz. It\u2019s a must have for every python developer.<\/li>\n<li><strong>Cython<\/strong> &#8211; an extension language for the CPython runtime. It translates Python code to fast C code and supports calling external C and C++ code natively.<\/li>\n<li><strong>Pandas<\/strong> &#8211; a library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series. Pandas is free software released under the three-clause BSD license<\/li>\n<li><strong>Statsmodels<\/strong> &#8211; a Python module that allows users to explore data, estimate statistical models, and perform statistical tests. An extensive list of descriptive statistics, statistical tests, plotting functions, and result statistics are available for different types of data and each estimator.<\/li>\n<li><strong>scikit-learn<\/strong> &#8211; is an open source library for the Python. It features various classification, regression and clustering algorithms including support vector machines, logistic regression, naive Bayes, random forests, gradient boosting, k-means and DBSCAN, and is designed to interoperate with the Python numerical and scientific libraries NumPy and SciPy.<\/li>\n<li><strong>Theano<\/strong> &#8211; uses NumPy-like syntax to optimize and evaluate mathematical expressions. What sets Theano apart is that it takes advantage of the computer\u2019s GPU in order to make data-intensive calculations up to 100x faster than the CPU alone. Theano\u2019s speed makes it especially valuable for deep learning and other computationally complex tasks.<\/li>\n<li><strong>TensorFlow<\/strong> &#8211; another high-profile entrant into machine learning, developed by Google as an open-source successor to DistBelief, their previous framework for training neural networks. TensorFlow uses a system of multi-layered nodes that allow you to quickly set up, train, and deploy artificial neural networks with large datasets. It\u2019s what allows Google to identify objects in photos or understand spoken words in its voice-recognition app.<\/li>\n<li><strong>Scrapy<\/strong> &#8211; an aptly named library for creating spider bots to systematically crawl the web and extract structured data like prices, contact info, and URLs. Originally designed for web scraping, Scrapy can also extract data from APIs.<\/li>\n<li><strong>Pattern<\/strong> &#8211; combines the functionality of Scrapy and NLTK in a massive library designed to serve as an out-of-the-box solution for web mining, NLP, machine learning, and network analysis. Its tools include a web crawler; APIs for Google, Twitter, and Wikipedia; and text-analysis algorithms like parse trees and sentiment analysis that can be performed with just a few lines of code.<\/li>\n<li><strong>Seaborn<\/strong> &#8211; a popular visualization library that builds on matplotlib\u2019s foundation. The first thing you\u2019ll notice about Seaborn is that its default styles are much more sophisticated than matplotlib\u2019s. Beyond that, Seaborn is a higher-level library, meaning it\u2019s easier to generate certain kinds of plots, including heat maps, time series, and violin plots.<\/li>\n<li><strong>Bokeh<\/strong> &#8211; another great visualization library is Bokeh, which is aimed at interactive visualizations. In contrast to the previous library, this one is independent of Matplotlib. The main focus of Bokeh, as we already mentioned, is interactivity and it makes its presentation via modern browsers in the style of Data-Driven Documents<\/li>\n<li><strong>Keras<\/strong> &#8211; an open-source library for building Neural Networks at a high-level of the interface, and it is written in Python. It is minimalistic and straightforward with high-level of extensibility. It uses Theano or TensorFlow as its backends, but Microsoft makes its efforts now to integrate CNTK (Microsoft\u2019s Cognitive Toolkit) as a new back-end.<\/li>\n<\/ul>\n<p>Understanding all these, you are officially an expert!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>There are two classes of Python users, those who use Python for management scripting and web development, and those who use Python for scientific computing. According to many, Python is winning the war against R in the field of machine learning. As machine learning becomes ever more important and popular, so is Python. This article [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8,9,4,3],"tags":[27,31,37,39,36,34,29,32,5,33,35,38,28,30],"class_list":["post-137","post","type-post","status-publish","format-standard","hentry","category-dl","category-ml","category-python","category-software","tag-anaconda","tag-fabric","tag-ipython","tag-machine-learning","tag-matplotlib","tag-numpy","tag-pip","tag-pytest","tag-python","tag-restful","tag-scipy","tag-tensorflow","tag-virtualenv","tag-wheel"],"_links":{"self":[{"href":"https:\/\/xiaohaionline.com\/index.php\/wp-json\/wp\/v2\/posts\/137","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/xiaohaionline.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/xiaohaionline.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/xiaohaionline.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/xiaohaionline.com\/index.php\/wp-json\/wp\/v2\/comments?post=137"}],"version-history":[{"count":42,"href":"https:\/\/xiaohaionline.com\/index.php\/wp-json\/wp\/v2\/posts\/137\/revisions"}],"predecessor-version":[{"id":221,"href":"https:\/\/xiaohaionline.com\/index.php\/wp-json\/wp\/v2\/posts\/137\/revisions\/221"}],"wp:attachment":[{"href":"https:\/\/xiaohaionline.com\/index.php\/wp-json\/wp\/v2\/media?parent=137"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/xiaohaionline.com\/index.php\/wp-json\/wp\/v2\/categories?post=137"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/xiaohaionline.com\/index.php\/wp-json\/wp\/v2\/tags?post=137"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}