Changes

Jump to navigation Jump to search
4,851 bytes added ,  08:08, 11 September 2024
m
Line 6: Line 6:  
===Arithmetic===
 
===Arithmetic===
 
  <nowiki>+    Addition
 
  <nowiki>+    Addition
  -    Substraction
+
          -    Substraction
  *    Multiplication
+
          *    Multiplication
  /    Division
+
          /    Division
  **  Power
+
          **  Power
  %    Reminder
+
          %    Reminder
  //  Floor division (Reminder is removed)</nowiki>
+
          //  Floor division (Reminder is removed)</nowiki>
 
===Comparison===
 
===Comparison===
 
  <nowiki>
 
  <nowiki>
  ==  Equal  
+
          ==  Equal  
  !=  Not equal
+
          !=  Not equal
  >    Greater
+
          >    Greater
  >=  Greater or equal
+
          >=  Greater or equal
  <    Smaller
+
          <    Smaller
  <=  Smaller or equal
+
          <=  Smaller or equal
  <>  Similar to !=</nowiki>
+
          <>  Similar to !=</nowiki>
 
===Assignment===
 
===Assignment===
 
  <nowiki>
 
  <nowiki>
  =    Simple assignment
+
          =    Simple assignment
  +=  Add and as
+
          +=  Add and as
  -=  Substract and  assignment
+
          -=  Substract and  assignment
  *=  Multiply and assignment
+
          *=  Multiply and assignment
  /=  Divide and assignment
+
          /=  Divide and assignment
  %=  Modulus and assignment
+
          %=  Modulus and assignment
  **=  Exponent and assignment
+
          **=  Exponent and assignment
  //=  Floor Divisionn and assignment</nowiki>
+
          //=  Floor Divisionn and assignment</nowiki>
    
===Bitwise operators===
 
===Bitwise operators===
 
They perform operations on binary terms. a= 8 → 100; b= 9 → 101; a & b → 100
 
They perform operations on binary terms. a= 8 → 100; b= 9 → 101; a & b → 100
 
  <nowiki>
 
  <nowiki>
  $    Binary AND
+
          $    Binary AND
  |    Binary OR
+
          |    Binary OR
  ^    Binary XOR
+
          ^    Binary XOR
  ~    Binary complement
+
          ~    Binary complement
  <<  Binary left shift
+
          <<  Binary left shift
  >>  Binary right shift</nowiki>
+
          >>  Binary right shift</nowiki>
    
===Logic===
 
===Logic===
 
  <nowiki>
 
  <nowiki>
  and
+
          and
  or
+
          or
  not</nowiki>
+
          not</nowiki>
    
===Membership operators===
 
===Membership operators===
Line 54: Line 54:  
==Variables==
 
==Variables==
 
===Numbers===
 
===Numbers===
 +
 +
====0 padding 2 digits====
 +
<syntaxhighlight lang="python3">
 +
print("{:02d}".format(1))
 +
</syntaxhighlight>
 +
 
===String===
 
===String===
 
String assingment:<br />
 
String assingment:<br />
Line 115: Line 121:  
Removes an item from a list.<br />  
 
Removes an item from a list.<br />  
 
example: a = [1, 2, 3, 4, 5] del a[0] returns [2, 3, 4, 5]
 
example: a = [1, 2, 3, 4, 5] del a[0] returns [2, 3, 4, 5]
 +
 +
<br />
 +
 +
====List comprehension====
 +
flatten list<syntaxhighlight lang="python3">
 +
def flatten(list_of_lists):
 +
    return [element for secondary_list in list_of_lists for element in secondary_list ]
 +
 +
a = [[1,2,3], [3,4,5], ["a", "b"]]
 +
flatten(a)
 +
 +
Out[29]: [1, 2, 3, 3, 4, 5, 'a', 'b']
 +
</syntaxhighlight><br />
    
====Tuple====
 
====Tuple====
Line 260: Line 279:  
</source>
 
</source>
    +
===Print Exception===
 +
<syntaxhighlight lang="python3">
 +
import traceback
 +
 +
def bug():
 +
    my_dict = {'a': 9}
 +
    try:
 +
        return my_dict['b']
 +
    except KeyError:
 +
        print(traceback.format_exc())
 +
        return None
 +
</syntaxhighlight><br />
 
==Loops==
 
==Loops==
 
===For===
 
===For===
Line 293: Line 324:  
==Regular Expressions==
 
==Regular Expressions==
 
  <nowiki>
 
  <nowiki>
    ^    → Matches the beginning of a line
+
            ^    → Matches the beginning of a line
    $    → Matches the end of a line
+
            $    → Matches the end of a line
    .    → Matches any character
+
            .    → Matches any character
    \s    → Matches any whitespace
+
            \s    → Matches any whitespace
    \S    → Matches any non-whitespace
+
            \S    → Matches any non-whitespace
    *    → Repeats a character 0 or more times
+
            *    → Repeats a character 0 or more times
    *?    → Repeats a character 0 or more times (non-greedy)
+
            *?    → Repeats a character 0 or more times (non-greedy)
    +      → Repeats a character 1 or more times
+
            +      → Repeats a character 1 or more times
    +?    → Repeats a character 1 or more times (non-greedy)
+
            +?    → Repeats a character 1 or more times (non-greedy)
  [aeiou] → Matches a single character in the listed set
+
          [aeiou] → Matches a single character in the listed set
  [^XYZ]  → Matches a single character NOT in the listed set
+
          [^XYZ]  → Matches a single character NOT in the listed set
  [a-z0-9] → The set of characters can include a range
+
          [a-z0-9] → The set of characters can include a range
    (    → Indicates where string extraction is to start
+
            (    → Indicates where string extraction is to start
    )    → Indicates where string extraction is to end</nowiki>  
+
            )    → Indicates where string extraction is to end</nowiki>  
 
   \    → Escape character
 
   \    → Escape character
 
===Regular Expression Module===
 
===Regular Expression Module===
Line 425: Line 456:  
     return counter
 
     return counter
 
</source>
 
</source>
 +
 +
==Run System Commands==
 +
 +
===Python >= 3.5===
 +
<syntaxhighlight lang="python3">
 +
def _run_command(command):
 +
    log.debug("Command: {}".format(command))
 +
    result = subprocess.run(command, shell=True, capture_output=True)
 +
 +
    if result.stderr:
 +
        raise subprocess.CalledProcessError(
 +
            returncode=result.returncode,
 +
            cmd=result.args,
 +
            stderr=f"{result.stdout}\n{result.stderr}"
 +
        )
 +
    if result.stdout:
 +
        log.debug("Command Result: {}".format(result.stdout.decode('utf-8')))
 +
    return result
 +
</syntaxhighlight>
    
==Class==
 
==Class==
Line 465: Line 515:  
'''Hiding attributes'''
 
'''Hiding attributes'''
 
attributes that start with a __ wont be visible to others<br />
 
attributes that start with a __ wont be visible to others<br />
 +
 +
===Subclasing builtins===
 +
 +
====Perfect dict subclass====
 +
<syntaxhighlight lang="python3">
 +
# has a ton of errors: https://stackoverflow.com/questions/3387691/how-to-perfectly-override-a-dict
 +
 +
class LowerDict(dict):
 +
    __slots__ = ()
 +
 +
    def _process_args(mapping=(), **kwargs):
 +
        if hasattr(mapping, items):
 +
            mapping = getattr(mapping, items)()
 +
        return ((ensure_lower(k), v) for k, v in chain(mapping, getattr(kwargs, items)()))
 +
 +
    def __init__(self, mapping=(), **kwargs):
 +
        super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
 +
 +
    def __getitem__(self, k):
 +
        return super(LowerDict, self).__getitem__(ensure_lower(k))
 +
    def __setitem__(self, k, v):
 +
        return super(LowerDict, self).__setitem__(ensure_lower(k), v)
 +
 +
    def __delitem__(self, k):
 +
        return super(LowerDict, self).__delitem__(ensure_lower(k))
 +
 +
    def get(self, k, default=None):
 +
        return super(LowerDict, self).get(ensure_lower(k), default)
 +
 +
    def setdefault(self, k, default=None):
 +
        return super(LowerDict, self).setdefault(ensure_lower(k), default)
 +
 +
    def pop(self, k, v=_RaiseKeyError):
 +
        if v is _RaiseKeyError:
 +
            return super(LowerDict, self).pop(ensure_lower(k))
 +
        return super(LowerDict, self).pop(ensure_lower(k), v)
 +
 +
    def update(self, mapping=(), **kwargs):
 +
        super(LowerDict, self).update(self._process_args(mapping, **kwargs))
 +
    def __contains__(self, k):
 +
        return super(LowerDict, self).__contains__(ensure_lower(k))
 +
 +
    def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
 +
        return type(self)(self)
 +
 +
    @classmethod
 +
    def fromkeys(cls, keys, v=None):
 +
        return super(LowerDict, cls).fromkeys((ensure_lower(k) for k in keys), v)
 +
 +
    def __repr__(self):
 +
        return '{0}({1})'.format(type(self).__name__, super(LowerDict, self).__repr__())
 +
</syntaxhighlight>
 +
 +
====Not so perfect dict like object====
 +
<syntaxhighlight lang="python3">
 +
from collections.abc import MutableMapping
 +
 +
 +
class TransformedDict(MutableMapping):
 +
    """A dictionary that applies an arbitrary key-altering
 +
      function before accessing the keys"""
 +
 +
    def __init__(self, *args, **kwargs):
 +
        self.store = dict()
 +
        self.update(dict(*args, **kwargs))  # use the free update to set keys
 +
 +
    def __getitem__(self, key):
 +
        return self.store[self._keytransform(key)]
 +
 +
    def __setitem__(self, key, value):
 +
        self.store[self._keytransform(key)] = value
 +
 +
    def __delitem__(self, key):
 +
        del self.store[self._keytransform(key)]
 +
 +
    def __iter__(self):
 +
        return iter(self.store)
 +
   
 +
    def __len__(self):
 +
        return len(self.store)
 +
 +
    def _keytransform(self, key):
 +
        return key
 +
</syntaxhighlight>
 +
 
==os.system()==
 
==os.system()==
 
To execute a Linux command from Python:
 
To execute a Linux command from Python:
Line 733: Line 868:  
nano ~/.pypirc
 
nano ~/.pypirc
 
  <nowiki>[distutils]
 
  <nowiki>[distutils]
  index-servers =
+
          index-servers =
    pypi
+
            pypi
    pypitest
+
            pypitest
 
+
         
  [pypi]
+
          [pypi]
  repository=https://upload.pypi.org/legacy/
+
          repository=https://upload.pypi.org/legacy/
  username=your_username
+
          username=your_username
  password=your_password
+
          password=your_password
 
+
         
  [pypitest]
+
          [pypitest]
  repository=https://testpypi.python.org/pypi
+
          repository=https://testpypi.python.org/pypi
  username=your_username
+
          username=your_username
  password=your_password</nowiki>
+
          password=your_password</nowiki>
 
Adjust .pypirc permissions
 
Adjust .pypirc permissions
 
  chmod 600 ~/.pypirc
 
  chmod 600 ~/.pypirc
Line 823: Line 958:  
nano setup.cfg
 
nano setup.cfg
 
  <nowiki>[metadata]
 
  <nowiki>[metadata]
  description-file = README.md</nowiki>
+
          description-file = README.md</nowiki>
    
nano LICENSE
 
nano LICENSE
 
  <nowiki>The MIT License
 
  <nowiki>The MIT License
 
+
         
  SPDX short identifier: MIT
+
          SPDX short identifier: MIT
 
+
         
  Copyright <YEAR> <COPYRIGHT HOLDER>
+
          Copyright <YEAR> <COPYRIGHT HOLDER>
 
+
         
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
          Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 
+
         
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
          The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
+
         
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</nowiki>
+
          THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</nowiki>
 
Test and upload
 
Test and upload
 
<source lang="bash">python setup.py register -r pypitest
 
<source lang="bash">python setup.py register -r pypitest
Line 850: Line 985:  
nano ~/.pip/pip.conf
 
nano ~/.pip/pip.conf
 
  <nowiki>[global]
 
  <nowiki>[global]
  index-url= http://10.255.0.21/pypi/simple
+
          index-url= http://10.255.0.21/pypi/simple
  trusted-host= 10.255.0.21</nowiki>
+
          trusted-host= 10.255.0.21</nowiki>
    
==Using pip behind proxy==
 
==Using pip behind proxy==
Line 859: Line 994:  
Create the file ~/.pypirc
 
Create the file ~/.pypirc
 
  <nowiki>[distutils]
 
  <nowiki>[distutils]
  index-servers =
+
          index-servers =
      pypi
+
              pypi
      pypitest
+
              pypitest
 
+
         
  [pypi]
+
          [pypi]
      repository=https://pypi.python.org/pypi
+
              repository=https://pypi.python.org/pypi
      username=
+
              username=
      password=
+
              password=
 
+
         
  [pypitest]
+
          [pypitest]
      repository=https://test.pypi.org/legacy
+
              repository=https://test.pypi.org/legacy
      username=
+
              username=
      password=
+
              password=
  </nowiki>
+
          </nowiki>
    
Test
 
Test
Line 881: Line 1,016:  
  python setup.py register -r pypi
 
  python setup.py register -r pypi
 
  python setup.py sdist upload -r pypi
 
  python setup.py sdist upload -r pypi
 +
 +
== requirements.txt ==
 +
 +
=== Platform conditional ===
 +
<syntaxhighlight lang="text">
 +
psycopg2-binary~=2.9.7; platform_system == "Linux"
 +
psycopg2~=2.9.6; platform_system == "Windows"
 +
</syntaxhighlight>
    
==AWS boto3 EC2==
 
==AWS boto3 EC2==

Navigation menu