<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>python on Deep Blue</title>
    <link>https://blog.dustbreak.com/categories/python/</link>
    <description>Recent content in python on Deep Blue</description>
    <generator>Hugo -- gohugo.io</generator>
    <lastBuildDate>Tue, 06 Jul 2021 21:33:41 +0800</lastBuildDate><atom:link href="https://blog.dustbreak.com/categories/python/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Python Newbie 3</title>
      <link>https://blog.dustbreak.com/posts/python_newbie_3/</link>
      <pubDate>Tue, 06 Jul 2021 21:33:41 +0800</pubDate>
      
      <guid>https://blog.dustbreak.com/posts/python_newbie_3/</guid>
      <description>1. The walrus operator Walrus operator is the coolest feature that was added in the Python 3.8 update python codes.
start = input(&amp;#34;Do you want to start(y/n)?&amp;#34;) print(start == &amp;#34;y&amp;#34;) # double parentheses here # using parentheses with the walrus operator is encouraged print((start := input(&amp;#34;Do you want to start(y/n)?&amp;#34;)) == &amp;#34;y&amp;#34;) # With parentheses if (sum := 10 + 5) &amp;gt; 10: print(sum) #return 15 # Without parentheses if sum := 10 + 5 &amp;gt; 10: print(sum) #return True a = [1, 2, 3, 4] if (n := len(a)) &amp;gt; 3: print(f&amp;#34;List is too long ({n} elements, expected &amp;lt;= 3)&amp;#34;) 2.</description>
      <content:encoded><![CDATA[<h2 id="1-the-walrus-operator">1. The walrus operator</h2>
<p>Walrus operator is the coolest feature that was added in the Python 3.8 update python codes.</p>
<pre tabindex="0"><code>start = input(&#34;Do you want to start(y/n)?&#34;)
print(start == &#34;y&#34;)


# double parentheses here 
# using parentheses with the walrus operator is encouraged
print((start := input(&#34;Do you want to start(y/n)?&#34;)) == &#34;y&#34;)
</code></pre><pre tabindex="0"><code># With parentheses
if (sum := 10 + 5) &gt; 10:
    print(sum) #return 15 
    
# Without parentheses 
if sum := 10 + 5 &gt; 10:
    print(sum) #return True
</code></pre><pre tabindex="0"><code>a = [1, 2, 3, 4]
if (n := len(a)) &gt; 3:
    print(f&#34;List is too long ({n} elements, expected &lt;= 3)&#34;)
</code></pre><h2 id="2-positional-only-parameters">2. Positional-only parameters</h2>
<p>There is a new function parameter syntax <code>/</code> to indicate that some function parameters must be specified positionally and cannot be used as keyword arguments.</p>
<pre tabindex="0"><code>def name(positional_only_parameters, /, positional_or_keyword_parameters, *, keyword_only_parameters):
</code></pre><pre tabindex="0"><code>&gt;&gt;&gt; def f(a,b,/,**kwargs):
...   print(a,b,kwargs)
...
&gt;&gt;&gt; f(10,20,a=1,b=2,c=3)
10 20 {&#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3}
</code></pre><pre tabindex="0"><code>def do_nothing(a, b, /):
  print(a, b)

&gt;&gt;&gt; do_nothing(1, 2)
1, 2

&gt;&gt;&gt; do_nothing(a=1, b=2)
Traceback (most recent call last):
  File &#34;&lt;stdin&gt;&#34;, line 1, in &lt;module&gt;
TypeError: do_nothing() takes no keyword arguments
</code></pre>]]></content:encoded>
    </item>
    
    <item>
      <title>Python Newbie 2</title>
      <link>https://blog.dustbreak.com/posts/python_newbie_2/</link>
      <pubDate>Wed, 28 Apr 2021 20:15:41 +0800</pubDate>
      
      <guid>https://blog.dustbreak.com/posts/python_newbie_2/</guid>
      <description>To make your codes more beautiful and more readable, try to use below checker to scan your python codes.
1. mypy Mypy is an optional static type checker for Python.
from typing import Union, Any, List, Optional, NoReturn, Dict, Tuple, Annotated, AnyStr def fib(n: int) -&amp;gt; Iterator[int]: a, b = 0, 1 while a &amp;lt; n: yield a a, b = b, a + b Repo here.
Mypy supports reading configuration settings from a file.</description>
      <content:encoded><![CDATA[<p>To make your codes more beautiful and more readable, try to use below checker to scan your python codes.</p>
<h2 id="1-mypy">1. mypy</h2>
<p>Mypy is an optional static type checker for Python.</p>
<pre tabindex="0"><code>from typing import Union, Any, List, Optional, NoReturn, Dict, Tuple, Annotated, AnyStr

def fib(n: int) -&gt; Iterator[int]:
    a, b = 0, 1
    while a &lt; n:
        yield a
        a, b = b, a + b
</code></pre><p>Repo <a href="https://github.com/python/mypy">here</a>.</p>
<p>Mypy supports reading configuration settings from a file.</p>
<pre tabindex="0"><code># Global options:

[mypy]
python_version = 3.9
warn_return_any = True
warn_unused_configs = True

# Per-module options:

[mypy-mycode.foo.*]
disallow_untyped_defs = True

[mypy-mycode.bar]
warn_return_any = False

[mypy-somelibrary]
ignore_missing_imports = True
</code></pre><p>More configs <a href="https://mypy.readthedocs.io/en/stable/config_file.html">here</a>.</p>
<h2 id="2-pylint">2. pylint</h2>
<p>Pylint is a tool that checks for errors in Python code, tries to enforce a coding standard and looks for <a href="https://martinfowler.com/bliki/CodeSmell.html">code smells</a>. The default coding style used by Pylint is close to <a href="https://www.python.org/dev/peps/pep-0008/">PEP 8</a>. You can change config file to apply Google Style.</p>
<pre tabindex="0"><code>[MASTER]

# Specify a configuration file.
#rcfile=

# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=

# Files or directories to be skipped. They should be base names, not
# paths.
ignore=CVS

# Pickle collected data for later comparisons.
persistent=yes
</code></pre><p>pylintrc sample <a href="https://github.com/PyCQA/pylint/blob/master/pylintrc">here</a>.</p>
<p>docs <a href="http://pylint.pycqa.org/en/latest/intro.html">here</a>.</p>
]]></content:encoded>
    </item>
    
    <item>
      <title>Python Newbie 1</title>
      <link>https://blog.dustbreak.com/posts/python_newbie_1/</link>
      <pubDate>Sat, 24 Apr 2021 19:02:41 +0800</pubDate>
      
      <guid>https://blog.dustbreak.com/posts/python_newbie_1/</guid>
      <description>1. functions def name_of_function(): &amp;#39;&amp;#39;&amp;#39; python function name should be snake chasing &amp;#39;&amp;#39;&amp;#39; Arbitary arguments *args **kwargs
def func(*args): &amp;#39;&amp;#39;&amp;#39; will get a tuple &amp;#39;&amp;#39;&amp;#39; print(args) def func(**kwargs): &amp;#39;&amp;#39;&amp;#39; will get a dictionary &amp;#39;&amp;#39;&amp;#39; if &amp;#39;fruit&amp;#39; in kwargs: print(f&amp;#34;choice is {kwargs[&amp;#39;fruit&amp;#39;]}&amp;#34;) func(fruit=&amp;#39;apple&amp;#39;,veggie=&amp;#39;lettuce&amp;#39;) 2. yield What does the &amp;ldquo;yield&amp;rdquo; keyword do?
the-python-yield-keyword-explained</description>
      <content:encoded><![CDATA[<h2 id="1-functions">1. functions</h2>
<pre tabindex="0"><code>def name_of_function():
  &#39;&#39;&#39;
  python function name should be snake chasing
  &#39;&#39;&#39;
</code></pre><p>Arbitary arguments <code>*args</code> <code>**kwargs</code></p>
<pre tabindex="0"><code>def func(*args):
  &#39;&#39;&#39;
  will get a tuple
  &#39;&#39;&#39;
  print(args)
</code></pre><pre tabindex="0"><code>def func(**kwargs):
  &#39;&#39;&#39;
  will get a dictionary
  &#39;&#39;&#39;
  if &#39;fruit&#39; in kwargs:
    print(f&#34;choice is {kwargs[&#39;fruit&#39;]}&#34;)
    
func(fruit=&#39;apple&#39;,veggie=&#39;lettuce&#39;)
</code></pre><h2 id="2-yield">2. yield</h2>
<p><a href="https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do">What does the &ldquo;yield&rdquo; keyword do?</a></p>
<p><a href="https://pyzh.readthedocs.io/en/latest/the-python-yield-keyword-explained.html">the-python-yield-keyword-explained</a></p>
]]></content:encoded>
    </item>
    
    <item>
      <title>Python Newbie 0</title>
      <link>https://blog.dustbreak.com/posts/python_newbie_0/</link>
      <pubDate>Tue, 06 Apr 2021 19:55:41 +0800</pubDate>
      
      <guid>https://blog.dustbreak.com/posts/python_newbie_0/</guid>
      <description>1. How to save lines to list in only one line def read_config(config): with open(config, &amp;#39;r&amp;#39;) as f: return list(map(lambda item: item.strip(&amp;#39;\n&amp;#39;), f.readlines())) 2. How to get value from nested dictionary def safe_get(dct, keys): for key in keys.split(&amp;#34;.&amp;#34;): try: dct = dct[key] except: return None return dct 3. How to rewrite the file import json with open (filename, &amp;#39;r+&amp;#39;) as json_file: ... json_file.seek(0,0) json.dump(data, json_file) 4. How to eliminate duplicate values in list sth = list(set(sth)) 5.</description>
      <content:encoded><![CDATA[<h2 id="1-how-to-save-lines-to-list-in-only-one-line">1. How to save lines to list in only one line</h2>
<pre tabindex="0"><code>def read_config(config):
    with open(config, &#39;r&#39;) as f:
        return list(map(lambda item: item.strip(&#39;\n&#39;), f.readlines()))
</code></pre><h2 id="2-how-to-get-value-from-nested-dictionary">2. How to get value from nested dictionary</h2>
<pre tabindex="0"><code>def safe_get(dct, keys):
    for key in keys.split(&#34;.&#34;):
        try:
            dct = dct[key]
        except:
            return None
    return dct
</code></pre><h2 id="3-how-to-rewrite-the-file">3. How to rewrite the file</h2>
<pre tabindex="0"><code>import json
with open (filename, &#39;r+&#39;) as json_file:
  	...
    json_file.seek(0,0)
    json.dump(data, json_file)
</code></pre><h2 id="4-how-to-eliminate-duplicate-values-in-list">4. How to eliminate duplicate values in list</h2>
<pre tabindex="0"><code>sth = list(set(sth))
</code></pre><h2 id="5-how-to-create-or-remove-dirs-safely">5. How to create or remove dirs safely</h2>
<pre tabindex="0"><code>import os, shutil

os.makedirs(&#34;temp&#34;, exist_ok=True)

if os.path.exists(&#34;temp&#34;) and os.path.isdir(&#34;temp&#34;): shutil.rmtree(&#34;temp&#34;)
</code></pre><h2 id="6-how-to-remove-prefix">6. How to remove prefix</h2>
<p>Python 3.9 or 3.9+</p>
<pre tabindex="0"><code># 0. Remove prefix from the string
s0=&#34;abcPYTHONabc&#34;
s0.removeprefix(&#34;abc&#34;)
#Output:PYTHONabc
s0.lstrip(&#34;abc&#34;)
#Output:PYTHONabc

# 1.The parameters of removeprefix() are considered as a substring. But parameters of lstrip() are considered as a set of characters
s1 = &#34;abcbcacPYTHONabc&#34;
s1.removeprefix(&#34;abc&#34;)
#Output:bcacPYTHONabc
s1.lstrip(&#34;abc&#34;)
#Output:PYTHONabc

# 2. removeprefix won&#39;t remove multiple copies of a prefix. But lstrip() will remove multiple copies of a prefix.
s2=&#34;abcabcPYTHONabc&#34;
s2.lstrip(&#34;abc&#34;)
#Output:PYTHONabc
s2.removeprefix(&#34;abc&#34;)
#Output:abcPYTHONabc

# 3. If the parameter is not mentioned in lstrip(), it will remove leading whitespaces. But if the parameter is not mentioned in removeprefix(), it will raise TypeError.
s3=&#34;   PYTHON&#34;
s3.lstrip()
#Output:PYTHON
s3.removeprefix()
#Output:TypeError: str.removeprefix() takes exactly one argument (0 given)

# 4. If the parameter mentioned is not found at the beginning of the string means, both methods will return a copy of the string.
s4=&#34;PYTHONabc&#34;
s4.lstrip(&#34;abc&#34;)
#Output:PYTHONabc
s4.removeprefix(&#34;abc&#34;)
#Output:PYTHONabc
</code></pre><p>before Python 3.9</p>
<pre tabindex="0"><code># 1. strip lstrip rstrip
str=&#34;abcbcxyyyyabcbc&#34;
str.strip(&#34;abc&#34;)
#Output:xyyyy
str.lstrip(&#34;abc&#34;)
#Output:xyyyyabcbc
str.rstrip(&#34;abc&#34;)
#Output:abcbcxyyyy

# 2. re.sub()
import re
pattern_suffix=r&#34;abc$&#34;
pattern_prefix=r&#34;^abc&#34;
s=&#34;abcPYTHONacbcabc&#34;
s_suffix=re.sub(pattern_suffix,&#34;&#34;,s) #Output:abcPYTHONacbc
s_prefix=re.sub(pattern_prefix,&#34;&#34;,s) #Output:PYTHONacbcabc

# 3. str.startswith()
s3=&#34;abcabcPythonacbcabc&#34;
if (s3.startswith(&#34;abc&#34;)):
    print (s3.replace(&#34;abc&#34;,&#34;&#34;,1))
#Output:abcPythonacbcabc
</code></pre><h2 id="reference">Reference</h2>
<p><a href="https://medium.com/dev-genius/new-string-methods-to-remove-prefixes-and-suffixes-in-python-3-9-4d5b3a5b034f">remove prefix</a></p>
]]></content:encoded>
    </item>
    
  </channel>
</rss>
