Skip to content

6 Code tips and tricks

Shahm Najeeb edited this page Nov 21, 2024 · 11 revisions

Logicytics Coding Tips

Here are some additional tips to help you write clean, efficient, and maintainable code for Logicytics, These include some already made custom libraries, some special GLOBAL variables and some special functions that can be used to make your life easier.

Custom scripts

Tip

The file _MOD_SKELETON.py describe the use cases as well, check it out!

Custom LOG class

For more professionals who can understand how the project wrapper actually works, you may utilise special mechanism's

To use Logs with its special settings, just modify the log = Log() line of code with any of the following parameters in dictionary format:

from __lib_class import *

if __name__ == "__main__":
    log = Log({
        "filename": "../ACCESS/LOGS/Logicytics.log", # Specifies the path to the log file.
        "use_colorlog": True, # A boolean indicating whether to use colored logging output - Keep it `True`.
        "log_level": DEBUG, # Sets the logging level. Better leave it as the `DEBUG` variable.
        "debug_color": "cyan", # Color for debug messages.
        "info_color": "green", # Color for info messages.
        "warning_color": "yellow", # Color for warning messages.
        "error_color": "red", # Color for error messages.
        "critical_color": "red", # Color for critical messages.
        "exception_color": "red", # Color for exception messages.
        "colorlog_fmt_parameters": "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", # Format string for colored log messages.
    })

Always use the log object to log messages, instead of using print() directly. Use the following format:

from __lib_class import *

if __name__ == "__main__":
    log = Log()

Where Log() is the default settings, you can change it to your liking - Using {"log_level": DEBUG} etc.

Text based logging

If for some reason you need to log something, but cant hardcode the log type, and may use a string for that purpose, then use the following line:

from __lib_class import *

if __name__ == "__main__":
    log = Log()

log.string("MESSAGE", "LOG_TYPE")

Replace MESSAGE with the text to actually be logged Replace LOG_TYPE with the following available strings:

"INFO": log.info
"WARNING": log.warning
"ERROR": log.error
"CRITICAL": log.critical
Anything Else: log.debug

Tip

Its case insensitive, and understands minor shortcuts (like crit for critical!)

Caution

If the value LOG_TYPE is incorrect, it gives a Internal error message. Won't produce a crash though!

Create Line Separation in log

To create a new line on the log being generated, use the following code:

from __lib_class import *

if __name__ == "__main__":
    log = Log()

log.newline()

This can work with the above two features, and doesn't actually need DEBUG to be true,

Note

This creates a new line with separators for both the terminal AND log file,

Log Decorator

Any function can use this new decorator, by using the following code:

from __lib_class import *

if __name__ == "__main__":
    log = Log()

@log.function
def main()
    pass # Place logic here

main()

When this is run, it logs the time it started and ended and outputs its speed/time taken in debug mode, this makes it very easy to debug code later, and find which segments need optimisation

An example of how it works can be seen in _MOD_SKELETON.py

Although this will fail and not work if you don't follow its proper initialisation:

  • It must initialised log properly
  • The function must be a main function, not a side-function - as in, do_this can use this decorator, while __do_this_part shouldn't as it help's the function do_this continue
  • It must be the last decorator, so if there is more than 1 decorator, the line order, it should be last (i.e it should execute the function first)

Example of a don't:

from __lib_class import *

# DONT: Failed to initialise log in the beginning of the script

class Main:
    @log.function
    @classmethod  # The classmethod surpasses the log.function, this is not allowed, as then log.function doesn't get a callable method, this should switch order.
    def main(cls):
        return cls.__main_helper()

    @staticmethod
    @log.function  # This is a side-function, it is intended to not execute by itself, so it shouldn't have the decorator
    def __main_helper():
        return "Example of helper"

main()

Tip

Do use this as it really will help in debugging and optimisation's in the long run.

Custom Libraries

Many custom libraries are used to reduce redundancy - they are more of a local python file that is imported. The always start with the prefix __lib_ and are .py files

They hold very powerful and useful values, to learn more about their documentation,

Library Class

Global Variables and Dictionaries

Variable Name Description
DEBUG Value from config.json - DEBUG on or off (bool)
VERSION The current version of the local project
CURRENT_FILES You may ignore this as they can't help you develop anything, its used by the debugger to check if your files are intact

Note

These do not have the custom log.function decorator, and so will not produce the debug logs for them

Custom Classes and Functions

Note

Only functions that are useful for development is shown here

Class.Method_Name Description Argument use case
FileManagement.open_file(file, use_full_path)

Opens a file or folder in default application, usually read mode, does not execute it

file: str -> Relative or complete path must be used, if no file extension is given it will consider it as a directory
use_full_path: bool -> If the file variable is a full static path, place True, defaults to False

Actions.unzip(zip_path)

Unzips a ZIP file given simply

zip_path: str -> Relative or complete path must be used, file extension should be .zip - Not really recommended to use -

Actions.run_command(command)

Runs a command and auto parses, decodes and returns the command’s value, useful to execute shell commands - Don't use this for file execution

command: str -> Must be complete command like what you type on the shell itself

Execute.script(script_path)

Executes the script and returns all its output, auto-parses and decodes and attempts unblocking scripts

script_path: str -> Only the file name or the dynamic file name and its path from the CODE directory, don't use full paths or full code.
Returns: list[list[str]] or None -> If it's Python, it automatically returns None; if not, it returns the output in a 2D list, to autoparse the logging. After executing this, use Log().execute_log_parse(OUTPUT_OF_THIS_FUNCTION) to actually get the log printed out in console etc, Although it must use the conventional printing rule #6a

Check.uac()

Checks if the UAC is disabled or not -> bool

N/A

Check.admin()

Checks if running as admin or not -> bool

N/A

Important

The Execute.script(script_path) is finicky with it's return statements for logging, and so I advice using it as follows Log().parse_execution(Execute.script(script_path))

Warning

The reason Actions.unzip(zip_path) is unrecommended is because it may unzip files it shouldn't, and hasn't been tested outside its use-case

Tip

We have omitted the __lib_log.py documentation as its from the repo AlgoPy, check it out to understand more on the custom logging mechanism - Here is the direct documentation of the class Log. This project has made minor modifications on it though, these minor modification can be found here.

Credits

Acknowledge your contributions appropriately in the CREDITS.md file. Use the following template when asked to add your contributions in the PR:

### File-Created/CONTRIBUTION by MAIN-Username
What you did, created, removed, refactored, fixed, or discovered.
- [Your GitHub Username](https://github.com/YourGitHubLink)
- [Your GitHub Username](https://github.com/YourGitHubLink) etc...

This ensures proper attribution and recognition for your efforts.

Tip

This is also found in the PR template!


By following these guidelines and practices, you can effectively contribute to open-source projects, enhancing both your skills and the broader community's knowledge and tools.


Clone this wiki locally