Python: Script structure

Python: Script structure

I decided to make some Python notes. Since there is a ton of information about Python, these notes will be mostly for my reference but if they help anyone - it will be great. The best way to understand it - try it and make a note:) starting with the basic script structure:

#!/usr/bin/env python
 
# """Module docstring."""
 
# Imports
import time
import sys
 
# Module Constants
CONSTANT_VARIABLE = "Probably shouldn't be changed"
 
# Module "Global" Variables
global_variable_file = "file.txt"
 
# Module Functions and Classes
def main(*args):
    """Main script function.
 
# Check to see if this file is the "__main__" script being executed
if __name__ == '__main__':
    _, *script_args = sys.argv
    main(*script_args)
  • #!/usr/bin/env python: Tells the shell the interpreter to “execute” the script.
  • #“”Module docstring.”””: docstrings. All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings.
  • #Imports: Import other code into the script
  • #Module Constants: all-CAPS variable names that probably shouldn’t be changed
  • #Module “Global” Variables: Every function and class will have to these variables
  • #Module Functions and Classes: Creates and stores new functions or class definitions available to run in the code
  • #__name__ = __main__: When script is executed, it is given the internal __name__ = __main__, when module is imported, __name__ = __ {func name}__

Best way to import modules:

import mod
[...]
 
# and call the function in {module}.{func} format
x = mod.func(4)  # func is a part of mod's namespace
No alt text provided for this image

PEP8

PEP 8 -- Style Guide for Python Code. There are several tools that help to check the code for conformance:

pycodestyle can check the code for conformance:

ciscos:dgolovach$ pycodestyle parse-ise.py 
parse-ise.py:13:1: E303 too many blank lines (6)
parse-ise.py:37:80: E501 line too long (107 > 79 characters)
parse-ise.py:38:80: E501 line too long (103 > 79 characters)
parse-ise.py:43:80: E501 line too long (89 > 79 characters)
parse-ise.py:86:1: E303 too many blank lines (4)
parse-ise.py:102:5: E722 do not use bare 'except'

autopep8 can automatically reformat code in the PEP 8 style. It fixes most of the formatting issues that are reported by pycodestyle.

here --in-place is to make changes to files in place. 

ciscos:dgolovach$ autopep8 --in-place parse-ise.py 
ciscos:dgolovach$ pycodestyle parse-ise.py 
parse-ise.py:33:80: E501 line too long (107 > 79 characters)
parse-ise.py:34:80: E501 line too long (103 > 79 characters)
parse-ise.py:39:80: E501 line too long (89 > 79 characters)
parse-ise.py:40:80: E501 line too long (81 > 79 characters)
parse-ise.py:96:5: E722 do not use bare 'except'

Pylint is a python linter that checks the source code, acts as a bug and quality checker and has more verification checks and options than just PEP8(Python style guide).

No alt text provided for this image

To customize pylint we can configure it at the project-level, user-level or global-level .

  • create a /etc/pylintrc for default global configuration
  • create a ~/pylintrc for default user configuration
  • Or create a pylintrc file

To create a pylintrc file pylint --generate-rcfile > pylintrc , which creates a template pylintrc(with comments) which can be customized as required.

For example, to set the max-line-length to 88 (default is 100):

No alt text provided for this image
No alt text provided for this image

Docstrings

Depending on the complexity:

def add(a, b):
    """Add two numbers and return the result."""
    return a + b
def random_number_generator(arg1, arg2):
    """
    Summary line.
    Extended description of function.
    Parameters
    ----------
    arg1 : int
        Description of arg1
    arg2 : str
        Description of arg2
    Returns
    -------
    int
        Description of return value
    """
    return 42

Docstrings are not ignored by the interpretator, and could be called to check doc for function: print.__doc__

>> print.__doc__

"print(value, …, sep=' ', end='\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."


A quick tip: We can use "_" to make the number more readable (Python 3.6) + swap values - easy:

No alt text provided for this image

Check out the link in the comments.

To view or add a comment, sign in

More articles by Dmitry Golovach

  • Swappable LLM Architectures: Building Flexible AI Systems

    In today's fast-evolving AI landscape, new models emerge daily, pricing structures change, and performance improvements…

  • OpenWebUI - ChatGPT-Style Interface

    Following up on my previous post about getting phi3 running locally - while the command line interface is functional, a…

  • Running Local AI with Ollama

    Why I Tried Running AI Locally I recently started running AI models on my own computer and it's been a game-changer…

  • Go meets Cisco using SSH

    I have already migrated some scripts from python to go, mostly with API. Decided to check how to SSH into network…

    1 Comment
  • How long did the function run in Go (Golang)

    Go (Golang) is fast. This phrase is everywhere.

  • WebApp: Cisco ISE and Python

    My previous post “Python and ISE Monitor Mode” was about how to collect access-session information from the switch and…

    9 Comments
  • Python and ISE Monitor Mode

    There are several ways to run ISE (wired) in monitor mode and AuthZ results: dACL, another VLAN, etc. It is always a…

    9 Comments
  • Python: Classes and Methods

    The simplest class in Python: Class and Instance Attributes Class attributes are attributes that are owned by the class…

    1 Comment
  • Python Dictionaries and JSON

    Dictionaries Dictionary – a collection of keys and values, unordered, changeable and indexed. >>> my_dict = {1: 'one'…

    5 Comments
  • Python: Apply config to multiple interfaces (with the condition)

    It is not about range feature:) After my post about how to get into the switch with “not sure” credentials, let’s…

    2 Comments

Insights from the community

Others also viewed

Explore topics