Package: type-config
Type config ⭐🐙Type-configis a small python library that let's you add custom types and validations to your config file.
The project's focus is on readability and maintainability, using a simple ini-like formatting.This project is being tested and very young. There could be updates soon and not everything might work as expected.If you find a problem, please write an issue, so I'll be able to solve it :)Table of contents (for github) 📝Type config ⭐🐙FeaturesDemoGetting startedInstallation 🔧InitialisationAdding optionsAdding typesGettersCreating a fileParsing a fileValidating an existing dictionaryMerging configurationsHealing a broken configurationError handling 🔧Contributing 💕Extra 🐙FeaturesDefine custom types for the validation of your config file's data, applied during parsingAutomatic formatting of your config filePossibility of recovering a corrupted (badly formatted) fileMerging configurations (useful when having CLI arguments and a config file)Attaching error and help messages to each option, for clear and effective communicationAdding type hints to your configuration file to help you during developmentDemoThis is how you would create atype_configobject:config=TypeConfig()# OR, if you want type hints in your config file:config=TypeConfig(type_hint=True)Adding options:config.add_option(option="shopping list",type="List>=3",help="What I have to buy",important_help="Must be a list of at least three items, separated by commas",)Adding a type (they can have descriptive names❗):config.add_type(type="List>=3",validate=lambdalist:len(list.split(","))>=3,cast=lambdalist:[item.trim()foriteminlist.split(",")],error="The list must have at least three items")This is how entries can look in a config file made withtype_config:shopping list=water, pasta, oil# !!! Must be a list of at least three items, separated by commas# What I have to buyor, if you want to see what type you are applying to the option:[List>=3] shopping list = water, pasta, oil# !!! Must be a list of at least three items, separated by commas# What I have to buyWhen you parse this file again, each option will be tested with their type's validating function and formatted using their casting function.If there are errors, the parsing won't crash; it will give you a list of which options failed and why, so that you can quickly understand what's wrong.Getting started 🔥Installation 🔧Install the package using pippipinstalltype_configInitialising the TypeConfig objectThe TypeConfig object is the main interface used by this library to help you handle configuration files and validation.config=TypeConfig(type_hint:bool=False)ParmeterDescriptionDefaulttype_hintWhether or not to add type hints to your config file.This initialises the class'self.type_hint, which can later on be changed directly by the user and is used byheal_configandcreate_config.FalseAdding optionsOptions are added using the methodadd_optionof a TypeConfig object.They hold many information useful when parsing and debugging.ParmeterDescriptionDefaultoptionThe option's nameRequiredtypeThe type associated with this optionRequiredhelpAn help string used to explain what the option does or what it is for.This is showed under the option in the config file.RequireddefaultA default value used when the option is left blankEmpty_stringcan_be_emptyWhether or not the option can be left without a value.The value that will be given isNone.Notice: default is applied when there is no value, so it's suggested using this option while leavingdefaultempty.Falseimportant_helpExtra information that could be useful when writing the option's valueEmpty_stringAdding typesTypes are added using the methodadd_typeof a TypeConfig object.They are used for data validation.ParmeterDescriptionDefaulttypeThe type's nameRequiredvalidateA function that returns a boolean, which is used to validate the option's value.RequiredcastA function that "casts" a specific type upon the option's value, effectively transforming it from string to the desired type.RequirederrorA message describing what could be the reason when the option's value is considered invalid.This is showed under the option in the config file.RequiredGettersYou can get a COPY of the options and types of a TypeConfig object by usingget_optionsandget_types.
These are to be used for testing, debugging or visualization, not for modifying the existing values.MethodDescriptionget_optionsGet all of the options added so far to the TypeConfig objectget_typesGet all of the types added so far to the TypeConfig objectCreating a fileYou can obtain the formatted text of a config file with thecreate_configmethod of a TypeConfig's object.
Ifself.type_hintis set toTrue, type hints will be added before each option. This DOES NOT have any effect on the parsing are are just "hints" for the developer.The optional argumentvalues_to_injectcan be very useful for testing; this can allow you to have a json file with values that have to be set but do not have a default value (or have an invalid value), and test your application dynamically, reducing the amount of maintainance required when adding or removing options (since you can generate a new config file in each test session).values_to_injectoverwrites only options that are present and only for that ouput; extra arguments are simply not taken into account and the TypeConfig instance's configuration is left untouched.ParmeterDescriptionDefaultvalues_to_injectA dictionary containing {option:value} pairs, which overwrite the default value written to the output.{}Notice: the library doesn't write directly to a file, instead it returns a string that can be written to an ini file.
This is done so that the user has more control over the output path and exceptions handling.Parsing a fileYou can extract your {option: value} pairs from a configuration file's content by using theparse_configmethod of a TypeConfig object.This method returns a tuple of two values, containing the configuration data (yet to be validated), represented as {option:value}, and a dictionary with errors that happened during parsing, represented as {option: error}.Notice: the library doesn't read directly from a file, instead it reads a string.
This is done so that the user has more control over the input path and exceptions handling.ParmeterDescriptionDefaultfile_contentA string representing the content config file to be parsed.RequiredValidating an existing dictionaryTo validate a dictionary containing your options, you can use thevalidate_configmethod of a TypeConfig object.
This can be useful for configurations coming from a file formatted by type_config and for options coming from theargparselibrary.It returns a dictionary with the validated data and a dictionary with errors that happened during validation (using the error linked to the option's type).
Errors are also raised when an option or a type are not part of the TypeConfig's instance's options and types.ParmeterDescriptionDefaultconfigA dictionary containing keys that are part of the TypeConfig's options.RequiredMerging configurationsTo merge two configurations, you can use themerge_configmethod of a TypeConfig object.This method creates a new dictionary containing {option:value}.The options' values priority is:Overwriting_config's valueOverwritable_config's valueDefault value from the TypeConfig objectraiseParsingErrorif option can't be empty, else value isNoneNotice: Falsy options are considered valid values. OnlyNonevalues are overwritten: to make sure the merging goes as expected, you might want to specify adefault=Noneif parsing cli arguments with argparse and usingstore_trueorstore_false.
Notice: no validation is done during this operation and only options present in the input configurations will be written to the result.ParmeterDescriptionDefaultOverwriting_configThe configuration dictionary which values will be preferred when merging.RequiredOverwritable_configThe configuration dictionary which values will be overwritten, if possible.RequiredHealing a broken configurationThe library has a method for "healing" badly formatted configurations, which is theheal_configmethod of a TypeConfig object. This method maintains {option: value} pairs if the option, equal sign and value are formatted correctly and the option is part of the TypeConfig object. This method also restores comments and whitespaces.Another use for this method is switching between a configuration file with type hints and one without. This behaviour is set byself.type_hint's value and can be useful during debugging.The returning value is a string (the healed configuration).Example:BrokenType] with a broken option #Added an inline commentI'm an option that dones't exist=ahahoption=my value# another inline comment# I changed the help linewill become:[BrokenType] with a broken option=default# !!! This are the important_help# And this is the help line[BrokenType] option=my value# !!! This are the important_help# And this is the original help lineParmeterDescriptionDefaultfile_contentA string representing the broken file content to restore.RequiredKnown bugs:Heal_configdoes not remove duplicate options for now; a fix is planned.Error Handling 🔧This library has only two kinds of errors:ParsingErrorandValidationError.They can be imported using:fromtype_config.errorsimportParsingError,ValidationErrorThis is a list of when they are used (all of these errors should be handled internally):ErrorSituationsMethodsParsingError- When an option  isn't part of the TypeConfig's object configuration- When an option that can't be left empty is None/Falsyparse_configValidationError-  When a type or an option isn't part of the TypeConfig's object configuration- When an option that can't be left empty is None/Falsy- When a value is invalid (Custom error message)prase_config,validate_configContributing 💕Feel free to open issues asking for more information or to reach out to me!Please make sure all thetestsare passing before opening a pull request. You can usepytestfor this.Please use types when possible (you can be helped bypyrightormypy).Please don't reformat the file in the same commit as your refactoring/contribution (if you want to, useblack); this is best done in its own commit, to make clear what changed in which commit.Please do not use abbreviations when naming variables or functions (I have an hard time understanding them :( ).Please appendFeat,Refactor,Fix,Formatto make clear what you've contributed on.Extra 🐙Built with love atRecurse Center