{"id":5705,"date":"2017-12-30T22:54:25","date_gmt":"2017-12-30T22:54:25","guid":{"rendered":"http:\/\/putridparrot.com\/blog\/?p=5705"},"modified":"2017-12-31T13:40:43","modified_gmt":"2017-12-31T13:40:43","slug":"python-basics","status":"publish","type":"post","link":"https:\/\/putridparrot.com\/blog\/python-basics\/","title":{"rendered":"Python basics"},"content":{"rendered":"<p>I&#8217;ve used Python (or more specifically IronPython) in the past to use Python as a scripting engine for my app. but never really bothered with Python beyond that. However, I decided I need to spend a little more time with Python, so am going to post a few &#8220;getting started&#8221; posts, starting with this one&#8230;<\/p>\n<p><em>Note: This post any others on Python are aimed at developers coming from another language, such as C#, Java or C++. So I will not be going over every capability of the language but will aim to cover those main areas  of syntax etc. to simply get things working in Python.<\/em><\/p>\n<p><strong>Python basics<\/strong><\/p>\n<p>Python files are usually saved with the .py extension and is interpreted, although there are apps for compiling the scripts to executables. <\/p>\n<p>Python is a dynamic language, hence we do not need to declare the type of a variable.<\/p>\n<p>Python uses whitespace and indentation to denote blocks of code, i.e. in C#, Java etc. we&#8217;d use curly braces { } to denote a block of code whereas Python expects the code blocks to be tabbed, for example in C# we might have<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic int Pi()\r\n{\r\n   return 3.14;\r\n}\r\n<\/pre>\n<p>the same function in Python would be <\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef pi():\r\n    return 3.14\r\n<\/pre>\n<p>This also demonstrates creating a function in Python (see Functions, below for more information on function definitions).<\/p>\n<p>Also notice that Python does not use line termination like the semi-colon in C#. Java etc. This means if we need to extend our code onto another line we can use the backslash, i.e.<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef pi():\r\n    return \\\r\n    3.14\r\n<\/pre>\n<p><strong>Types<\/strong><\/p>\n<p>Python is a dynamically typed language which has good and bad points. This basically means when we declare a variable name it&#8217;s automatically created and it&#8217;s type is automatically declared based upon it&#8217;s usage. The type can change as we assign different types to the variable, for example<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nvalue = &quot;Hello World&quot;\r\n# value is of type str\r\nvalue = 123\r\n# value is now of type int\r\n<\/pre>\n<p>Note: # is used for a single line comment, we can use &#8220;&#8221;&#8221; to start and end a block of code to use as multi-line comments, although technically speaking these denote multi-line strings.<\/p>\n<p><a href=\"https:\/\/docs.python.org\/2\/library\/types.html\" rel=\"noopener\" target=\"_blank\">Python types<\/a> include the usual types, such as a string (str), int, long, float, boolean along with complex types, tuples and more.<\/p>\n<p>If we need to find the <em>type<\/em> at runtime then we can use the <em>type<\/em> method, for example<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nvalue = (1, &quot;Hello&quot;)\r\nprint(type(value))\r\n<\/pre>\n<p>In this code, the first line creates a tuple and the next line outputs (to the console) the type of the value variable, in this case the output will be<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;class 'tuple'&gt;\r\n<\/pre>\n<p><strong>Enumerations<\/strong><\/p>\n<p>Enumerations are declared via the Enum type, we need to import the enum module and then we can declare our Enum subclassed type as follows<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport enum\r\n\r\nclass Gender(enum.Enum):\r\n    Male = 1,\r\n    Female = 2\r\n\r\n# in use\r\ng = Gender.Female\r\n<\/pre>\n<p><strong>Functions<\/strong><\/p>\n<p>Python allows us to define function using the def keyword, here the example we introduced earlier<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef pi():\r\n    return 3.14\r\n<\/pre>\n<p><em>def<\/em> is used to declare or define our function, arguments may be passed within the parenthesis, in this instance no arguments exist. Finally we end the function declaration using the colon. The actual statements that are executed within the function are then below the declaration and the code is indented.  <\/p>\n<p>Executing functions uses pretty standard syntax, i.e.<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nvalue = pi()\r\n<\/pre>\n<p>Although Python does a good job of type inference when we have code like the following<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef add(a, b):\r\n    return a + b\r\n<\/pre>\n<p>we have a situation where both of the following bits of code work<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nstrValue = add(&quot;2&quot;, &quot;3&quot;)\r\nintValue = add(2, 3)\r\n<\/pre>\n<p>but in the first instance we get the string &#8220;23&#8221; and in the second we get the int 5.<\/p>\n<p>Obviously if our intent of that the <em>add<\/em> function it for numerical types then we will need to give type hints, for example<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef add(a: float, b: float) -&gt; float:\r\n    return a + b\r\n<\/pre>\n<p>The strange thing here (if you&#8217;re used to similar techniques in F#, for example) is that running the previous example of the add function with strings and ints will still work, i.e. still returns &#8220;23&#8221; and 5. So it&#8217;s debatable how useful hints are. Certainly PyCharm will display a &#8220;hint&#8221; over the string arguments and tell us the expected type, but ultimately we can still pass in a different types for the add function arguments.<\/p>\n<p>If you want to include type hints but not show them in your source or if you want to hint on existing code that you do not (or cannot) edit. Then you can include a .pyi file along with the .py file including the type\/function etc. and separate the hints from the actual implementation. So for example our .py file might have<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef add(a, b):\r\n    return a + b\r\n<\/pre>\n<p>and the file with the same name but .pyi extension would have<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef add(a: float, b: float) -&gt; float: ...\r\n<\/pre>\n<p><strong>Object Orientated<\/strong><\/p>\n<p>Python allows us to define classes uses the class keyword, for example<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport http.client\r\n\r\nclass WebClient:\r\n        def __init__(self):\r\n            self.url = &quot;www.google.co.uk&quot;\r\n            self.method = &quot;GET&quot;\r\n\r\n        def submit(self):\r\n            connection = http.client.HTTPConnection(self.url)\r\n            connection.request(self.method, &quot;\/&quot;)\r\n            response = connection.getresponse()\r\n            data = response.read()\r\n            print(response.status, response.reason)\r\n            print(data)\r\n\r\nclient = WebClient()\r\n<\/pre>\n<p>The __init__ function is the equivalent of a constructor and self is analogous to <em>this<\/em> in C#. Within the __init__ we have declared new variables along with some default values, i.e. the url and method variables.<\/p>\n<p>In the case where we do not have anything to setup\/initialize in the __init__ function we can use the pass keyword. Here&#8217;s an example of this along with how we can derived\/subclass a type<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nclass Animal:\r\n    def __init__(self):\r\n        pass\r\n\r\nclass Dog(Animal):\r\n    def __init__(self):\r\n        self.legs = 4\r\n<\/pre>\n<p>A good old, OO example whereby Animal is the base class and Dog subclasses this and adds functionality\/fields etc. <\/p>\n<p>As you&#8217;ve probably already noticed, Python doesn&#8217;t include a <em>new<\/em> keyword to create an instance of a class we simply use<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nanimal = Dog()\r\n<\/pre>\n<p><strong>Importing modules &#038; packages<\/strong><\/p>\n<p>Like most languages, we can create reusable source code modules (and packages) that can then be imported into our source code, for example let&#8217;s import a Python standard library for connecting to an HTTP endpoint<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport http.client\r\n\r\nconnection = http.client.HTTPConnection(&quot;www.google.co.uk&quot;)\r\nconnection.request(&quot;GET&quot;, &quot;\/&quot;)\r\nresponse = connection.getresponse()\r\ndata = response.read()\r\n<\/pre>\n<p>In the code above, we import the http.client library and then create an HTTPConnection instance which we then use to connect to google.co.uk.<\/p>\n<p>We can import multiple modules using comma separated values, i.e.<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport http.client, sys\r\n<\/pre>\n<p><strong>Creating modules &#038; packages<\/strong><\/p>\n<p>Modules are simply ways to define reusable code within separate files. Packages are is essence namespaces which can contain multiple packages and modules. <\/p>\n<p>To create a module, we simply create a file, for example web.py and include our functions and types etc. within that file, so web.py looks like this<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport http.client\r\n\r\nclass WebClient:\r\n        def __init__(self):\r\n            self.url = &quot;www.google.co.uk&quot;\r\n            self.method = &quot;GET&quot;\r\n\r\n        def submit(self):\r\n            connection = http.client.HTTPConnection(self.url)\r\n            connection.request(self.method, &quot;\/&quot;)\r\n            response = connection.getresponse()\r\n            data = response.read()\r\n            print(response.status, response.reason)\r\n            print(data)\r\n<\/pre>\n<p>and it our file that uses this module, we have the following<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport web\r\n\r\nclient = web.WebClient()\r\nclient.submit()\r\n<\/pre>\n<p>Packages now take this a little further. Still using the file based approach. Packages are simply directories with one or more module file, but every package <strong>must<\/strong> include a file named __init__.py which can be empty. This __init__.py file may contain an __all__ variable which defines what modules are exported, i.e. non-exported modules can be internal or private to the package or exported and visible to those using the package. For example our __init__.py file might look like this<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n__all__ = &#x5B;'WebClient']\r\n\r\n# example within multiple exports\r\n__all__ = &#x5B;'WebClient', 'SomethingElse']\r\n<\/pre>\n<p>However the above only seems to be used when using the alternate import syntax, for example<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom web import *\r\n<\/pre>\n<p><em>See the answers to <a href=\"https:\/\/stackoverflow.com\/questions\/44834\/can-someone-explain-all-in-python\" rel=\"noopener\" target=\"_blank\">Can someone explain __all__ in Python? <\/a> for much more information on the use of __all__.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;ve used Python (or more specifically IronPython) in the past to use Python as a scripting engine for my app. but never really bothered with Python beyond that. However, I decided I need to spend a little more time with Python, so am going to post a few &#8220;getting started&#8221; posts, starting with this one&#8230; [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[195],"tags":[],"class_list":["post-5705","post","type-post","status-publish","format-standard","hentry","category-python"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5705","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/comments?post=5705"}],"version-history":[{"count":16,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5705\/revisions"}],"predecessor-version":[{"id":5731,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5705\/revisions\/5731"}],"wp:attachment":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/media?parent=5705"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/categories?post=5705"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/tags?post=5705"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}