Metadata-Version: 2.4
Name: formax-py
Version: 0.8.0
Summary: High-performance Python model builder and validation engine with zero dependencies
Author-email: nshaibu <nafiushaibu1@gmail.com>
License:                     GNU GENERAL PUBLIC LICENSE
                               Version 3, 29 June 2007
        
         Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
         Everyone is permitted to copy and distribute verbatim copies
         of this license document, but changing it is not allowed.
        
                                    Preamble
        
          The GNU General Public License is a free, copyleft license for
        software and other kinds of works.
        
          The licenses for most software and other practical works are designed
        to take away your freedom to share and change the works.  By contrast,
        the GNU General Public License is intended to guarantee your freedom to
        share and change all versions of a program--to make sure it remains free
        software for all its users.  We, the Free Software Foundation, use the
        GNU General Public License for most of our software; it applies also to
        any other work released this way by its authors.  You can apply it to
        your programs, too.
        
          When we speak of free software, we are referring to freedom, not
        price.  Our General Public Licenses are designed to make sure that you
        have the freedom to distribute copies of free software (and charge for
        them if you wish), that you receive source code or can get it if you
        want it, that you can change the software or use pieces of it in new
        free programs, and that you know you can do these things.
        
          To protect your rights, we need to prevent others from denying you
        these rights or asking you to surrender the rights.  Therefore, you have
        certain responsibilities if you distribute copies of the software, or if
        you modify it: responsibilities to respect the freedom of others.
        
          For example, if you distribute copies of such a program, whether
        gratis or for a fee, you must pass on to the recipients the same
        freedoms that you received.  You must make sure that they, too, receive
        or can get the source code.  And you must show them these terms so they
        know their rights.
        
          Developers that use the GNU GPL protect your rights with two steps:
        (1) assert copyright on the software, and (2) offer you this License
        giving you legal permission to copy, distribute and/or modify it.
        
          For the developers' and authors' protection, the GPL clearly explains
        that there is no warranty for this free software.  For both users' and
        authors' sake, the GPL requires that modified versions be marked as
        changed, so that their problems will not be attributed erroneously to
        authors of previous versions.
        
          Some devices are designed to deny users access to install or run
        modified versions of the software inside them, although the manufacturer
        can do so.  This is fundamentally incompatible with the aim of
        protecting users' freedom to change the software.  The systematic
        pattern of such abuse occurs in the area of products for individuals to
        use, which is precisely where it is most unacceptable.  Therefore, we
        have designed this version of the GPL to prohibit the practice for those
        products.  If such problems arise substantially in other domains, we
        stand ready to extend this provision to those domains in future versions
        of the GPL, as needed to protect the freedom of users.
        
          Finally, every program is threatened constantly by software patents.
        States should not allow patents to restrict development and use of
        software on general-purpose computers, but in those that do, we wish to
        avoid the special danger that patents applied to a free program could
        make it effectively proprietary.  To prevent this, the GPL assures that
        patents cannot be used to render the program non-free.
        
          The precise terms and conditions for copying, distribution and
        modification follow.
        
                               TERMS AND CONDITIONS
        
          0. Definitions.
        
          "This License" refers to version 3 of the GNU General Public License.
        
          "Copyright" also means copyright-like laws that apply to other kinds of
        works, such as semiconductor masks.
        
          "The Program" refers to any copyrightable work licensed under this
        License.  Each licensee is addressed as "you".  "Licensees" and
        "recipients" may be individuals or organizations.
        
          To "modify" a work means to copy from or adapt all or part of the work
        in a fashion requiring copyright permission, other than the making of an
        exact copy.  The resulting work is called a "modified version" of the
        earlier work or a work "based on" the earlier work.
        
          A "covered work" means either the unmodified Program or a work based
        on the Program.
        
          To "propagate" a work means to do anything with it that, without
        permission, would make you directly or secondarily liable for
        infringement under applicable copyright law, except executing it on a
        computer or modifying a private copy.  Propagation includes copying,
        distribution (with or without modification), making available to the
        public, and in some countries other activities as well.
        
          To "convey" a work means any kind of propagation that enables other
        parties to make or receive copies.  Mere interaction with a user through
        a computer network, with no transfer of a copy, is not conveying.
        
          An interactive user interface displays "Appropriate Legal Notices"
        to the extent that it includes a convenient and prominently visible
        feature that (1) displays an appropriate copyright notice, and (2)
        tells the user that there is no warranty for the work (except to the
        extent that warranties are provided), that licensees may convey the
        work under this License, and how to view a copy of this License.  If
        the interface presents a list of user commands or options, such as a
        menu, a prominent item in the list meets this criterion.
        
          1. Source Code.
        
          The "source code" for a work means the preferred form of the work
        for making modifications to it.  "Object code" means any non-source
        form of a work.
        
          A "Standard Interface" means an interface that either is an official
        standard defined by a recognized standards body, or, in the case of
        interfaces specified for a particular programming language, one that
        is widely used among developers working in that language.
        
          The "System Libraries" of an executable work include anything, other
        than the work as a whole, that (a) is included in the normal form of
        packaging a Major Component, but which is not part of that Major
        Component, and (b) serves only to enable use of the work with that
        Major Component, or to implement a Standard Interface for which an
        implementation is available to the public in source code form.  A
        "Major Component", in this context, means a major essential component
        (kernel, window system, and so on) of the specific operating system
        (if any) on which the executable work runs, or a compiler used to
        produce the work, or an object code interpreter used to run it.
        
          The "Corresponding Source" for a work in object code form means all
        the source code needed to generate, install, and (for an executable
        work) run the object code and to modify the work, including scripts to
        control those activities.  However, it does not include the work's
        System Libraries, or general-purpose tools or generally available free
        programs which are used unmodified in performing those activities but
        which are not part of the work.  For example, Corresponding Source
        includes interface definition files associated with source files for
        the work, and the source code for shared libraries and dynamically
        linked subprograms that the work is specifically designed to require,
        such as by intimate data communication or control flow between those
        subprograms and other parts of the work.
        
          The Corresponding Source need not include anything that users
        can regenerate automatically from other parts of the Corresponding
        Source.
        
          The Corresponding Source for a work in source code form is that
        same work.
        
          2. Basic Permissions.
        
          All rights granted under this License are granted for the term of
        copyright on the Program, and are irrevocable provided the stated
        conditions are met.  This License explicitly affirms your unlimited
        permission to run the unmodified Program.  The output from running a
        covered work is covered by this License only if the output, given its
        content, constitutes a covered work.  This License acknowledges your
        rights of fair use or other equivalent, as provided by copyright law.
        
          You may make, run and propagate covered works that you do not
        convey, without conditions so long as your license otherwise remains
        in force.  You may convey covered works to others for the sole purpose
        of having them make modifications exclusively for you, or provide you
        with facilities for running those works, provided that you comply with
        the terms of this License in conveying all material for which you do
        not control copyright.  Those thus making or running the covered works
        for you must do so exclusively on your behalf, under your direction
        and control, on terms that prohibit them from making any copies of
        your copyrighted material outside their relationship with you.
        
          Conveying under any other circumstances is permitted solely under
        the conditions stated below.  Sublicensing is not allowed; section 10
        makes it unnecessary.
        
          3. Protecting Users' Legal Rights From Anti-Circumvention Law.
        
          No covered work shall be deemed part of an effective technological
        measure under any applicable law fulfilling obligations under article
        11 of the WIPO copyright treaty adopted on 20 December 1996, or
        similar laws prohibiting or restricting circumvention of such
        measures.
        
          When you convey a covered work, you waive any legal power to forbid
        circumvention of technological measures to the extent such circumvention
        is effected by exercising rights under this License with respect to
        the covered work, and you disclaim any intention to limit operation or
        modification of the work as a means of enforcing, against the work's
        users, your or third parties' legal rights to forbid circumvention of
        technological measures.
        
          4. Conveying Verbatim Copies.
        
          You may convey verbatim copies of the Program's source code as you
        receive it, in any medium, provided that you conspicuously and
        appropriately publish on each copy an appropriate copyright notice;
        keep intact all notices stating that this License and any
        non-permissive terms added in accord with section 7 apply to the code;
        keep intact all notices of the absence of any warranty; and give all
        recipients a copy of this License along with the Program.
        
          You may charge any price or no price for each copy that you convey,
        and you may offer support or warranty protection for a fee.
        
          5. Conveying Modified Source Versions.
        
          You may convey a work based on the Program, or the modifications to
        produce it from the Program, in the form of source code under the
        terms of section 4, provided that you also meet all of these conditions:
        
            a) The work must carry prominent notices stating that you modified
            it, and giving a relevant date.
        
            b) The work must carry prominent notices stating that it is
            released under this License and any conditions added under section
            7.  This requirement modifies the requirement in section 4 to
            "keep intact all notices".
        
            c) You must license the entire work, as a whole, under this
            License to anyone who comes into possession of a copy.  This
            License will therefore apply, along with any applicable section 7
            additional terms, to the whole of the work, and all its parts,
            regardless of how they are packaged.  This License gives no
            permission to license the work in any other way, but it does not
            invalidate such permission if you have separately received it.
        
            d) If the work has interactive user interfaces, each must display
            Appropriate Legal Notices; however, if the Program has interactive
            interfaces that do not display Appropriate Legal Notices, your
            work need not make them do so.
        
          A compilation of a covered work with other separate and independent
        works, which are not by their nature extensions of the covered work,
        and which are not combined with it such as to form a larger program,
        in or on a volume of a storage or distribution medium, is called an
        "aggregate" if the compilation and its resulting copyright are not
        used to limit the access or legal rights of the compilation's users
        beyond what the individual works permit.  Inclusion of a covered work
        in an aggregate does not cause this License to apply to the other
        parts of the aggregate.
        
          6. Conveying Non-Source Forms.
        
          You may convey a covered work in object code form under the terms
        of sections 4 and 5, provided that you also convey the
        machine-readable Corresponding Source under the terms of this License,
        in one of these ways:
        
            a) Convey the object code in, or embodied in, a physical product
            (including a physical distribution medium), accompanied by the
            Corresponding Source fixed on a durable physical medium
            customarily used for software interchange.
        
            b) Convey the object code in, or embodied in, a physical product
            (including a physical distribution medium), accompanied by a
            written offer, valid for at least three years and valid for as
            long as you offer spare parts or customer support for that product
            model, to give anyone who possesses the object code either (1) a
            copy of the Corresponding Source for all the software in the
            product that is covered by this License, on a durable physical
            medium customarily used for software interchange, for a price no
            more than your reasonable cost of physically performing this
            conveying of source, or (2) access to copy the
            Corresponding Source from a network server at no charge.
        
            c) Convey individual copies of the object code with a copy of the
            written offer to provide the Corresponding Source.  This
            alternative is allowed only occasionally and noncommercially, and
            only if you received the object code with such an offer, in accord
            with subsection 6b.
        
            d) Convey the object code by offering access from a designated
            place (gratis or for a charge), and offer equivalent access to the
            Corresponding Source in the same way through the same place at no
            further charge.  You need not require recipients to copy the
            Corresponding Source along with the object code.  If the place to
            copy the object code is a network server, the Corresponding Source
            may be on a different server (operated by you or a third party)
            that supports equivalent copying facilities, provided you maintain
            clear directions next to the object code saying where to find the
            Corresponding Source.  Regardless of what server hosts the
            Corresponding Source, you remain obligated to ensure that it is
            available for as long as needed to satisfy these requirements.
        
            e) Convey the object code using peer-to-peer transmission, provided
            you inform other peers where the object code and Corresponding
            Source of the work are being offered to the general public at no
            charge under subsection 6d.
        
          A separable portion of the object code, whose source code is excluded
        from the Corresponding Source as a System Library, need not be
        included in conveying the object code work.
        
          A "User Product" is either (1) a "consumer product", which means any
        tangible personal property which is normally used for personal, family,
        or household purposes, or (2) anything designed or sold for incorporation
        into a dwelling.  In determining whether a product is a consumer product,
        doubtful cases shall be resolved in favor of coverage.  For a particular
        product received by a particular user, "normally used" refers to a
        typical or common use of that class of product, regardless of the status
        of the particular user or of the way in which the particular user
        actually uses, or expects or is expected to use, the product.  A product
        is a consumer product regardless of whether the product has substantial
        commercial, industrial or non-consumer uses, unless such uses represent
        the only significant mode of use of the product.
        
          "Installation Information" for a User Product means any methods,
        procedures, authorization keys, or other information required to install
        and execute modified versions of a covered work in that User Product from
        a modified version of its Corresponding Source.  The information must
        suffice to ensure that the continued functioning of the modified object
        code is in no case prevented or interfered with solely because
        modification has been made.
        
          If you convey an object code work under this section in, or with, or
        specifically for use in, a User Product, and the conveying occurs as
        part of a transaction in which the right of possession and use of the
        User Product is transferred to the recipient in perpetuity or for a
        fixed term (regardless of how the transaction is characterized), the
        Corresponding Source conveyed under this section must be accompanied
        by the Installation Information.  But this requirement does not apply
        if neither you nor any third party retains the ability to install
        modified object code on the User Product (for example, the work has
        been installed in ROM).
        
          The requirement to provide Installation Information does not include a
        requirement to continue to provide support service, warranty, or updates
        for a work that has been modified or installed by the recipient, or for
        the User Product in which it has been modified or installed.  Access to a
        network may be denied when the modification itself materially and
        adversely affects the operation of the network or violates the rules and
        protocols for communication across the network.
        
          Corresponding Source conveyed, and Installation Information provided,
        in accord with this section must be in a format that is publicly
        documented (and with an implementation available to the public in
        source code form), and must require no special password or key for
        unpacking, reading or copying.
        
          7. Additional Terms.
        
          "Additional permissions" are terms that supplement the terms of this
        License by making exceptions from one or more of its conditions.
        Additional permissions that are applicable to the entire Program shall
        be treated as though they were included in this License, to the extent
        that they are valid under applicable law.  If additional permissions
        apply only to part of the Program, that part may be used separately
        under those permissions, but the entire Program remains governed by
        this License without regard to the additional permissions.
        
          When you convey a copy of a covered work, you may at your option
        remove any additional permissions from that copy, or from any part of
        it.  (Additional permissions may be written to require their own
        removal in certain cases when you modify the work.)  You may place
        additional permissions on material, added by you to a covered work,
        for which you have or can give appropriate copyright permission.
        
          Notwithstanding any other provision of this License, for material you
        add to a covered work, you may (if authorized by the copyright holders of
        that material) supplement the terms of this License with terms:
        
            a) Disclaiming warranty or limiting liability differently from the
            terms of sections 15 and 16 of this License; or
        
            b) Requiring preservation of specified reasonable legal notices or
            author attributions in that material or in the Appropriate Legal
            Notices displayed by works containing it; or
        
            c) Prohibiting misrepresentation of the origin of that material, or
            requiring that modified versions of such material be marked in
            reasonable ways as different from the original version; or
        
            d) Limiting the use for publicity purposes of names of licensors or
            authors of the material; or
        
            e) Declining to grant rights under trademark law for use of some
            trade names, trademarks, or service marks; or
        
            f) Requiring indemnification of licensors and authors of that
            material by anyone who conveys the material (or modified versions of
            it) with contractual assumptions of liability to the recipient, for
            any liability that these contractual assumptions directly impose on
            those licensors and authors.
        
          All other non-permissive additional terms are considered "further
        restrictions" within the meaning of section 10.  If the Program as you
        received it, or any part of it, contains a notice stating that it is
        governed by this License along with a term that is a further
        restriction, you may remove that term.  If a license document contains
        a further restriction but permits relicensing or conveying under this
        License, you may add to a covered work material governed by the terms
        of that license document, provided that the further restriction does
        not survive such relicensing or conveying.
        
          If you add terms to a covered work in accord with this section, you
        must place, in the relevant source files, a statement of the
        additional terms that apply to those files, or a notice indicating
        where to find the applicable terms.
        
          Additional terms, permissive or non-permissive, may be stated in the
        form of a separately written license, or stated as exceptions;
        the above requirements apply either way.
        
          8. Termination.
        
          You may not propagate or modify a covered work except as expressly
        provided under this License.  Any attempt otherwise to propagate or
        modify it is void, and will automatically terminate your rights under
        this License (including any patent licenses granted under the third
        paragraph of section 11).
        
          However, if you cease all violation of this License, then your
        license from a particular copyright holder is reinstated (a)
        provisionally, unless and until the copyright holder explicitly and
        finally terminates your license, and (b) permanently, if the copyright
        holder fails to notify you of the violation by some reasonable means
        prior to 60 days after the cessation.
        
          Moreover, your license from a particular copyright holder is
        reinstated permanently if the copyright holder notifies you of the
        violation by some reasonable means, this is the first time you have
        received notice of violation of this License (for any work) from that
        copyright holder, and you cure the violation prior to 30 days after
        your receipt of the notice.
        
          Termination of your rights under this section does not terminate the
        licenses of parties who have received copies or rights from you under
        this License.  If your rights have been terminated and not permanently
        reinstated, you do not qualify to receive new licenses for the same
        material under section 10.
        
          9. Acceptance Not Required for Having Copies.
        
          You are not required to accept this License in order to receive or
        run a copy of the Program.  Ancillary propagation of a covered work
        occurring solely as a consequence of using peer-to-peer transmission
        to receive a copy likewise does not require acceptance.  However,
        nothing other than this License grants you permission to propagate or
        modify any covered work.  These actions infringe copyright if you do
        not accept this License.  Therefore, by modifying or propagating a
        covered work, you indicate your acceptance of this License to do so.
        
          10. Automatic Licensing of Downstream Recipients.
        
          Each time you convey a covered work, the recipient automatically
        receives a license from the original licensors, to run, modify and
        propagate that work, subject to this License.  You are not responsible
        for enforcing compliance by third parties with this License.
        
          An "entity transaction" is a transaction transferring control of an
        organization, or substantially all assets of one, or subdividing an
        organization, or merging organizations.  If propagation of a covered
        work results from an entity transaction, each party to that
        transaction who receives a copy of the work also receives whatever
        licenses to the work the party's predecessor in interest had or could
        give under the previous paragraph, plus a right to possession of the
        Corresponding Source of the work from the predecessor in interest, if
        the predecessor has it or can get it with reasonable efforts.
        
          You may not impose any further restrictions on the exercise of the
        rights granted or affirmed under this License.  For example, you may
        not impose a license fee, royalty, or other charge for exercise of
        rights granted under this License, and you may not initiate litigation
        (including a cross-claim or counterclaim in a lawsuit) alleging that
        any patent claim is infringed by making, using, selling, offering for
        sale, or importing the Program or any portion of it.
        
          11. Patents.
        
          A "contributor" is a copyright holder who authorizes use under this
        License of the Program or a work on which the Program is based.  The
        work thus licensed is called the contributor's "contributor version".
        
          A contributor's "essential patent claims" are all patent claims
        owned or controlled by the contributor, whether already acquired or
        hereafter acquired, that would be infringed by some manner, permitted
        by this License, of making, using, or selling its contributor version,
        but do not include claims that would be infringed only as a
        consequence of further modification of the contributor version.  For
        purposes of this definition, "control" includes the right to grant
        patent sublicenses in a manner consistent with the requirements of
        this License.
        
          Each contributor grants you a non-exclusive, worldwide, royalty-free
        patent license under the contributor's essential patent claims, to
        make, use, sell, offer for sale, import and otherwise run, modify and
        propagate the contents of its contributor version.
        
          In the following three paragraphs, a "patent license" is any express
        agreement or commitment, however denominated, not to enforce a patent
        (such as an express permission to practice a patent or covenant not to
        sue for patent infringement).  To "grant" such a patent license to a
        party means to make such an agreement or commitment not to enforce a
        patent against the party.
        
          If you convey a covered work, knowingly relying on a patent license,
        and the Corresponding Source of the work is not available for anyone
        to copy, free of charge and under the terms of this License, through a
        publicly available network server or other readily accessible means,
        then you must either (1) cause the Corresponding Source to be so
        available, or (2) arrange to deprive yourself of the benefit of the
        patent license for this particular work, or (3) arrange, in a manner
        consistent with the requirements of this License, to extend the patent
        license to downstream recipients.  "Knowingly relying" means you have
        actual knowledge that, but for the patent license, your conveying the
        covered work in a country, or your recipient's use of the covered work
        in a country, would infringe one or more identifiable patents in that
        country that you have reason to believe are valid.
        
          If, pursuant to or in connection with a single transaction or
        arrangement, you convey, or propagate by procuring conveyance of, a
        covered work, and grant a patent license to some of the parties
        receiving the covered work authorizing them to use, propagate, modify
        or convey a specific copy of the covered work, then the patent license
        you grant is automatically extended to all recipients of the covered
        work and works based on it.
        
          A patent license is "discriminatory" if it does not include within
        the scope of its coverage, prohibits the exercise of, or is
        conditioned on the non-exercise of one or more of the rights that are
        specifically granted under this License.  You may not convey a covered
        work if you are a party to an arrangement with a third party that is
        in the business of distributing software, under which you make payment
        to the third party based on the extent of your activity of conveying
        the work, and under which the third party grants, to any of the
        parties who would receive the covered work from you, a discriminatory
        patent license (a) in connection with copies of the covered work
        conveyed by you (or copies made from those copies), or (b) primarily
        for and in connection with specific products or compilations that
        contain the covered work, unless you entered into that arrangement,
        or that patent license was granted, prior to 28 March 2007.
        
          Nothing in this License shall be construed as excluding or limiting
        any implied license or other defenses to infringement that may
        otherwise be available to you under applicable patent law.
        
          12. No Surrender of Others' Freedom.
        
          If conditions are imposed on you (whether by court order, agreement or
        otherwise) that contradict the conditions of this License, they do not
        excuse you from the conditions of this License.  If you cannot convey a
        covered work so as to satisfy simultaneously your obligations under this
        License and any other pertinent obligations, then as a consequence you may
        not convey it at all.  For example, if you agree to terms that obligate you
        to collect a royalty for further conveying from those to whom you convey
        the Program, the only way you could satisfy both those terms and this
        License would be to refrain entirely from conveying the Program.
        
          13. Use with the GNU Affero General Public License.
        
          Notwithstanding any other provision of this License, you have
        permission to link or combine any covered work with a work licensed
        under version 3 of the GNU Affero General Public License into a single
        combined work, and to convey the resulting work.  The terms of this
        License will continue to apply to the part which is the covered work,
        but the special requirements of the GNU Affero General Public License,
        section 13, concerning interaction through a network will apply to the
        combination as such.
        
          14. Revised Versions of this License.
        
          The Free Software Foundation may publish revised and/or new versions of
        the GNU General Public License from time to time.  Such new versions will
        be similar in spirit to the present version, but may differ in detail to
        address new problems or concerns.
        
          Each version is given a distinguishing version number.  If the
        Program specifies that a certain numbered version of the GNU General
        Public License "or any later version" applies to it, you have the
        option of following the terms and conditions either of that numbered
        version or of any later version published by the Free Software
        Foundation.  If the Program does not specify a version number of the
        GNU General Public License, you may choose any version ever published
        by the Free Software Foundation.
        
          If the Program specifies that a proxy can decide which future
        versions of the GNU General Public License can be used, that proxy's
        public statement of acceptance of a version permanently authorizes you
        to choose that version for the Program.
        
          Later license versions may give you additional or different
        permissions.  However, no additional obligations are imposed on any
        author or copyright holder as a result of your choosing to follow a
        later version.
        
          15. Disclaimer of Warranty.
        
          THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
        APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
        HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
        OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
        THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
        PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
        IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
        ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
        
          16. Limitation of Liability.
        
          IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
        WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
        THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
        GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
        USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
        DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
        PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
        EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
        SUCH DAMAGES.
        
          17. Interpretation of Sections 15 and 16.
        
          If the disclaimer of warranty and limitation of liability provided
        above cannot be given local legal effect according to their terms,
        reviewing courts shall apply local law that most closely approximates
        an absolute waiver of all civil liability in connection with the
        Program, unless a warranty or assumption of liability accompanies a
        copy of the Program in return for a fee.
        
                             END OF TERMS AND CONDITIONS
        
                    How to Apply These Terms to Your New Programs
        
          If you develop a new program, and you want it to be of the greatest
        possible use to the public, the best way to achieve this is to make it
        free software which everyone can redistribute and change under these terms.
        
          To do so, attach the following notices to the program.  It is safest
        to attach them to the start of each source file to most effectively
        state the exclusion of warranty; and each file should have at least
        the "copyright" line and a pointer to where the full notice is found.
        
            <one line to give the program's name and a brief idea of what it does.>
            Copyright (C) <year>  <name of author>
        
            This program is free software: you can redistribute it and/or modify
            it under the terms of the GNU General Public License as published by
            the Free Software Foundation, either version 3 of the License, or
            (at your option) any later version.
        
            This program is distributed in the hope that it will be useful,
            but WITHOUT ANY WARRANTY; without even the implied warranty of
            MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
            GNU General Public License for more details.
        
            You should have received a copy of the GNU General Public License
            along with this program.  If not, see <https://www.gnu.org/licenses/>.
        
        Also add information on how to contact you by electronic and paper mail.
        
          If the program does terminal interaction, make it output a short
        notice like this when it starts in an interactive mode:
        
            <program>  Copyright (C) <year>  <name of author>
            This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
            This is free software, and you are welcome to redistribute it
            under certain conditions; type `show c' for details.
        
        The hypothetical commands `show w' and `show c' should show the appropriate
        parts of the General Public License.  Of course, your program's commands
        might be different; for a GUI interface, you would use an "about box".
        
          You should also get your employer (if you work as a programmer) or school,
        if any, to sign a "copyright disclaimer" for the program, if necessary.
        For more information on this, and how to apply and follow the GNU GPL, see
        <https://www.gnu.org/licenses/>.
        
          The GNU General Public License does not permit incorporating your program
        into proprietary programs.  If your program is a subroutine library, you
        may consider it more useful to permit linking proprietary applications with
        the library.  If this is what you want to do, use the GNU Lesser General
        Public License instead of this License.  But first, please read
        <https://www.gnu.org/licenses/why-not-lgpl.html>.
        
Project-URL: Homepage, https://github.com/nshaibu/formax
Project-URL: Issues, https://github.com/nshaibu/formax/issues
Project-URL: CI, https://github.com/nshaibu/formax/actions
Keywords: data-validation,schema,dataclass,model,serialization,validation,class-builder,orm,formax
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: typing-extensions>=4.12.2
Provides-Extra: dev
Requires-Dist: coverage>=7.4.1; extra == "dev"
Requires-Dist: iniconfig==2.0.0; extra == "dev"
Requires-Dist: packaging==24.2; extra == "dev"
Requires-Dist: pluggy==1.5.0; extra == "dev"
Requires-Dist: pytest>=8.3.4; extra == "dev"
Requires-Dist: pytest-benchmark==5.2.3; extra == "dev"
Requires-Dist: pyflakes==3.2.0; extra == "dev"
Requires-Dist: mccabe==0.7.0; extra == "dev"
Requires-Dist: flake8==7.1.1; extra == "dev"
Requires-Dist: pycodestyle==2.12.1; extra == "dev"
Requires-Dist: flake8-black==0.3.6; extra == "dev"
Requires-Dist: black>=22.1.0; extra == "dev"
Requires-Dist: click==8.1.8; extra == "dev"
Requires-Dist: mypy-extensions==1.0.0; extra == "dev"
Requires-Dist: pathspec==0.12.1; extra == "dev"
Requires-Dist: platformdirs==4.3.6; extra == "dev"
Dynamic: license-file

# Formax

[![Build Status](https://github.com/nshaibu/formax/actions/workflows/python_package.yml/badge.svg)](https://github.com/nshaibu/formax/actions)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![Status](https://img.shields.io/pypi/status/formax.svg)](https://pypi.python.org/pypi/formax)
[![Latest](https://img.shields.io/pypi/v/formax.svg)](https://pypi.python.org/pypi/formax)
[![PyV](https://img.shields.io/pypi/pyversions/formax.svg)](https://pypi.python.org/pypi/formax)
[![codecov](https://codecov.io/gh/nshaibu/formax/graph/badge.svg?token=HBP9OC9IJJ)](https://codecov.io/gh/nshaibu/formax)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)


## Table of Contents
- [Overview](#overview)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Core Concepts](#core-concepts)
- [API Reference](#api-reference)
- [Validation](#validation)
   - [Nested Validation](#nested-validation)
   - [Self-References and Forward References](#self-References-and-forward-references)
- [Preformatters](#preformatters)
- [Serialization](#serialization)
  - [Model Formatters](#model-formatters)
    - [Custom Formatters](#custom-formatters)
- [Configuration](#configuration)
- [Advanced Usage](#advanced-usage)
- [Examples](#examples)
- [Contributing](#contributing)
- [License](#license)

## Overview

Formax is a Python library that extends the functionality of Python's native dataclass by providing built-in validation, serialisation, and support for custom validators. It is designed to be simple, modern, and based entirely on Python's standard library, making it perfect for projects requiring data validation and object-relational mapping (ORM) without relying on third-party dependencies.

### Key Features

- **Type and Value Validation**: Enforces type validation for fields using field annotations with built-in validators for common field types
- **Custom Validators**: Easily define custom validation functions for specific fields
- **Serialisation Support**: Instances can be serialised to JSON, dictionaries, and CSV formats
- **Lightweight and Fast**: Built entirely on Python's standard library with no external dependencies
- **Multiple Input Formats**: Accepts data in various formats, including JSON, dictionaries, CSV, etc.
- **Simple ORM Capabilities**: Build lightweight ORMs for basic data management

## Installation

### From PyPI
```bash
pip install formax
```

### From Source
```bash
git clone https://github.com/nshaibu/formax.git
cd formax
# Use the code directly in your project
```

## Quick Start

Here's a simple example to get you started:

```python
from formax import BaseModel

class Person(BaseModel):
    name: str
    age: int

# Create an instance
person = Person(name="Alice", age=30)
print(person)  # Person(name='Alice', age=30)

# Validation happens automatically
try:
    invalid_person = Person(name="Bob", age="not_a_number")
except TypeError as e:
    print(f"Validation failed: {e}")
```

## Core Concepts

### BaseModel

`BaseModel` is the foundation class that all your data models should inherit from. It provides:
- Automatic type validation
- Serialization capabilities
- Custom validation support
- Configuration options

### MiniAnnotated

`MiniAnnotated` is used to add metadata and validation rules to fields:

```python
from formax import BaseModel, MiniAnnotated, Attrib

class User(BaseModel):
    username: MiniAnnotated[str, Attrib(max_length=20)]
    age: MiniAnnotated[int, Attrib(gt=0, default=18)]
```

### Attrib

`Attrib` defines field attributes and validation rules:
- `default`: Default value for the field
- `default_factory`: Function to generate default value
- `pattern`: Regex pattern for string validation
- `validators`: List of custom validator functions
- `pre_formatter`: Function to format/preprocess the value before validation.
- `required`: Whether this field is required (default: False).
- `allow_none`: Whether None is allowed as a value (default: False).
- `gt`, `ge`, `lt`, `le`: Numeric comparison constraints.
- `min_length`, `max_length` (int, optional): Length constraints for sequences.

## API Reference

### BaseModel

The base class for all data models.

#### Class Methods

##### `loads(data, _format="dict")`
Load data from various formats into model instances.

**Parameters:**
- `data`: Input data (string, dict, or other format-specific data)
- `_format`: Format of input data (`"json"`, `"dict"`, `"csv"`)

**Returns:** Model instance or list of instances (for CSV)

**Example:**
```python
# From JSON string
json_data = '{"name": "John", "age": 30}'
person = Person.loads(json_data, _format="json")

# From dictionary
dict_data = {"name": "Alice", "age": 25}
person = Person.loads(dict_data, _format="dict")

# From CSV
csv_data = "name,age\nJohn,30\nAlice,25"
people = Person.loads(csv_data, _format="csv")
```

#### Instance Methods

##### `dump(_format="dict")`
Serialize the model instance to various formats.

**Parameters:**
- `_format`: Output format (`"json"`, `"dict"`, `"csv"`)

**Returns:** Serialized data in the specified format

**Example:**
```python
person = Person(name="John", age=30)

# To JSON string
json_output = person.dump(_format="json")

# To dictionary
dict_output = person.dump(_format="dict")
```

##### `__post_init__(self, **kwargs)`
Optional method for custom initialization logic.

**Example:**
```python
from typing import Optional
from dataclasses import InitVar

class DatabaseModel(BaseModel):
    id: int
    name: str
    database: InitVar[Optional[object]] = None
    
    def __post_init__(self, database):
        if database is not None:
            # Custom initialization logic
            self.id = database.get_next_id()
```

## Validation

### Type Validation

Formax automatically validates field types based on annotations:

```python
class Product(BaseModel):
    name: str
    price: float
    quantity: int
    is_available: bool
```

### Built-in Validators

Use `Attrib` to add built-in validation rules:

```python
class User(BaseModel):
    username: MiniAnnotated[str, Attrib(max_length=20)]
    age: MiniAnnotated[int, Attrib(gt=18)]
    email: MiniAnnotated[str, Attrib(pattern=r"^\S+@\S+\.\S+$")]
    score: MiniAnnotated[float, Attrib(default=0.0)]
```

### Custom Field Validators

Define custom validation functions:

### Validator Function Signature

All validators must follow this signature:

```python
@validator(['field_name', ...])
def validator_name(instance, value):
    """
    Args:
        value: The field value being validated
        instance: The model instance being created (access other fields)
    
    Raises:
        ValidationError: If validation fails
    """
    # Validation logic here

```

**Key points:**
- First parameter is an instance of the model
- `value` is the current field's value
- `instance` provides access to other fields for cross-field validation
- Raise `ValidationError` to fail validation

### Using Validators in Attrib

You can pass validator functions directly to `Attrib`:

```python
from formax.exceptions import ValidationError

def validate_not_kofi(instance: BaseModel, value: str):
    if value.lower() == "kofi":
        raise ValidationError("Kofi is not a valid name")

class Employee(BaseModel):
    name: MiniAnnotated[str, Attrib(validators=[validate_not_kofi])]
    department: str
```

### Method-based Validators

The `@validator` decorator allows you to define custom validation logic for one or more fields.

```python
from formax.decorators import validator
from formax.exceptions import ValidationError

class School(BaseModel):
    name: str
    students_count: int
    
    @validator(["name"])
    def validate_name(self, value):
        if len(value) > 50:
            raise ValidationError("School name too long")
    
    @validator(["students_count"])    
    def validate_students_count(self, value):
        if value < 0:
            raise ValidationError("Students count cannot be negative")
```

#### Global Validators

Apply validation rules to all fields:

```python
from formax.decorators import validator
from formax.exceptions import ValidationError

class StrictModel(BaseModel):
    field1: str
    field2: str
    field3: str
    
    @validator(["field1", "field2", "field3"])
    def validate(self, value, field):
        if isinstance(value, str) and len(value) > 100:
            raise ValidationError(f"Field {field.name} is too long")
```

#### Multi-Field Validators

You can apply the same validator to multiple fields by passing multiple field names:

```python
from formax import BaseModel, validator
from formax.exceptions import ValidationError

class School(BaseModel):
    name: str
    location: str
    students_count: int
    
    @validator(['name', 'location'])
    def validate_string_fields(self, value):
        """Ensure string fields are not too long."""
        if len(value) > 50:
            raise ValidationError("Field value is too long (max 50 characters)")
    
    @validator(['students_count'])
    def validate_students_count(self, value):
        """Ensure student count is positive."""
        if value < 0:
            raise ValidationError("Students count cannot be negative")

# Usage
school = School(name="KNUST", location="Kumasi", students_count=5000)
```

#### Cross-Field Validation

Validators can access other fields through the `instance` parameter for cross-field validation:

```python
from formax import BaseModel, validator
from formax.exceptions import ValidationError

class PasswordModel(BaseModel):
    password: str
    confirm_password: str
    
    @validator(['confirm_password'])
    def passwords_match(self, value):
        """Ensure password and confirm_password match."""
        if value != self.password:
            raise ValidationError("Passwords do not match")
        return value

# Usage
valid = PasswordModel(password="secret123", confirm_password="secret123")

try:
    invalid = PasswordModel(password="secret123", confirm_password="different")
except ValidationError as e:
    print(f"Validation failed: {e}")
```

#### Validator with Built-in Constraints

Combine `@validator` with `Attrib` constraints:

```python
from formax import BaseModel, MiniAnnotated, Attrib, validator
from formax.exceptions import ValidationError

class RangeModel(BaseModel):
    min_value: MiniAnnotated[int, Attrib(ge=0)]
    max_value: MiniAnnotated[int, Attrib(ge=0)]
    
    @validator(['max_value'])
    def validate_max_greater_than_min(self, value):
        """Ensure max_value is greater than min_value."""
        if value <= self.min_value:
            raise ValidationError("max_value must be greater than min_value")

# Usage
valid = RangeModel(min_value=10, max_value=20)

try:
    invalid = RangeModel(min_value=20, max_value=10)
except ValidationError as e:
    print(f"Validation failed: {e}")
```

### Validator Execution Order

Understanding the order of validation operations is important:

1. **Preformatters** - Transform raw input values (e.g., string → enum)
2. **Type Validation** - Check if value matches field type annotation
3. **Built-in Validators** - Apply `Attrib` constraints (max_length, gt, pattern, etc.)
4. **Custom Validators** - Apply `@validator` decorated methods

```python
from formax import BaseModel, MiniAnnotated, Attrib, validator, preformat
from formax.exceptions import ValidationError
from enum import Enum

class Priority(Enum):
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"

class Task(BaseModel):
    title: MiniAnnotated[str, Attrib(max_length=100)]
    priority: Priority
    
    @preformat(['priority'])
    def normalize_priority(self, value):
        """Step 1: Convert string to enum."""
        if isinstance(value, str):
            return Priority[value.upper()]
        return value
    
    @validator(['title'])
    def validate_title(self, value):
        """Step 4: Custom validation after type and built-in checks."""
        if value.lower().startswith("urgent"):
            self.priority = Priority.HIGH  # Can modify other fields

# Execution order:
# 1. preformat('priority'): "low" → Priority.LOW
# 2. Type check: Priority.LOW is Priority ✓
# 3. Built-in validator: len(title) <= 100 ✓
# 4. @validator('title'): custom logic
```

### Complex Validation Example

Here's a comprehensive example demonstrating multiple validation techniques:

```python
from formax import BaseModel, MiniAnnotated, Attrib, validator, preformat
from formax.exceptions import ValidationError
from enum import Enum
import re

class UserRole(Enum):
    ADMIN = "admin"
    USER = "user"
    GUEST = "guest"

class User(BaseModel):
    username: MiniAnnotated[str, Attrib(max_length=30)]
    email: MiniAnnotated[str, Attrib(pattern=r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")]
    password: str
    age: MiniAnnotated[int, Attrib(gt=13, default=18)]
    role: UserRole
    
    @preformat(['role'])
    def normalize_role(self, value):
        if isinstance(value, str):
            return UserRole[value.upper()]
    
    @validator(['username'])
    def validate_username(self, value):
        if not re.match(r"^[a-zA-Z0-9_]+$", value):
            raise ValidationError("Username can only contain letters, numbers, and underscores")
    
    @validator(['password'])
    def validate_password(self, value):
        if len(value) < 8:
            raise ValidationError("Password must be at least 8 characters long")
        if not re.search(r"[A-Z]", value):
            raise ValidationError("Password must contain at least one uppercase letter")
        if not re.search(r"[a-z]", value):
            raise ValidationError("Password must contain at least one lowercase letter")
        if not re.search(r"\d", value):
            raise ValidationError("Password must contain at least one digit")
    
    @validator(['age'])
    def validate_age(self, value):
        if value > 120:
            raise ValidationError("Age seems unrealistic")
    
    @validator(['role'])
    def validate_admin_age(self, value):
        if value == UserRole.ADMIN and self.age < 18:
            raise ValidationError("Admin users must be at least 18 years old")

# Usage
try:
    user = User(
        username="JohnDoe123",
        email="john@example.com",
        password="SecurePass123",
        age=25,
        role="ADMIN"
    )
    print(f"Created user: {user.username}")
except ValidationError as e:
    print(f"Validation failed: {e}")
```

### Validation Best Practices

1. **Single Responsibility**: Each validator should check one thing
   ```python
   # Good - separate validators
   @validator(['email'])
   def validate_email_format(instance, value):
       # Check format only
       pass
   
   @validator(['email'])
   def validate_email_unique(instance, value):
       # Check uniqueness only
       pass
   ```

2. **Clear Error Messages**: Be specific about what failed
   ```python
   @validator(['age'])
   def validate_age(self, value):
       if value < 0:
           raise ValidationError("Age cannot be negative")
       if value > 150:
           raise ValidationError("Age cannot exceed 150 years")
   ```

3. **Transform in Preformatters**: Use `@preformat` for data transformation before validation
   ```python
   @preformat(['status'])
   def normalize_status(self, value):
       return value.upper() if isinstance(value, str) else value
   
   @validator(['status'])
   def validate_status(instance, value):
       # Validate the already-normalized value
       pass
   ```

4. **Use Built-in Constraints First**: Prefer `Attrib` constraints over custom validators when possible
   ```python
   # Preferred
   age: MiniAnnotated[int, Attrib(gt=0, lt=150)]
   
   # Less preferred (but sometimes necessary for complex logic)
   @validator(['age'])
   def validate_age(instance, value):
       if not (0 < value < 150):
           raise ValidationError("Age must be between 0 and 150")
   ```

5. **Cross-Field Validation Order**: Be aware of field order when using cross-field validation
   ```python
   class Model(BaseModel):
       field_a: int
       field_b: int
       
       @validator(['field_b'])
       def validate_b(self, value):
           # instance.field_a is available because field_a is defined before field_b
           if value <= self.field_a:
               raise ValidationError("field_b must be greater than field_a")
   ```

## Nested Validation

Formax supports nested validation, allowing you to compose complex data models from simpler ones. When a field is annotated with another `BaseModel` class, the validation system automatically applies to the nested class and all its fields recursively. This enables you to build hierarchical data structures with comprehensive validation at every level.

### Basic Nested Validation

When you define a field using another `BaseModel` class, both the parent and nested models are fully validated:

```python
from formax import BaseModel

class School(BaseModel):
    name: str
    location: str

class Person(BaseModel):
    name: str
    school: School
```

Validators work seamlessly with nested models:

```python
from formax import BaseModel, MiniAnnotated, Attrib, validator, preformat
from formax.exceptions import ValidationError

class Address(BaseModel):
    street: str
    city: str
    postal_code: MiniAnnotated[str, Attrib(pattern=r"^\d{5}$")]
    
    @preformat(['city'])
    def format_city(self, value):
        """Ensure city name is capitalized."""
        return value.title()

class Person(BaseModel):
    name: str
    age: MiniAnnotated[int, Attrib(gt=0)]
    address: Address
    
    @validator(['name'])
    def validate_name(self, value):
        """Ensure name is not empty."""
        if not value.strip():
            raise ValidationError("Name cannot be empty")

# Nested validation happens automatically
person = Person(
    name="john doe",
    age=30,
    address={
        "street": "123 Main St",
        "city": "new york",
        "postal_code": "10001"
    }
)

print(person.name)  # Output: john doe
print(person.address.city)  # Output: New York (validated and transformed)
```

#### Instantiation Methods

You can instantiate nested models in two ways:

#### 1. Using Nested Model Instances

```python
# Create nested model first
school = School(name="KNUST", location="Kumasi")
person = Person(name="Nafiu", school=school)

print(person.name)  # Output: Nafiu
print(person.school.name)  # Output: KNUST
print(person.school.location)  # Output: Kumasi
```

#### 2. Using Dictionary Auto-Conversion

```python
# Pass dictionary - automatically converted to School instance
person = Person(
    name="Nafiu",
    school={"name": "KNUST", "location": "Kumasi"}
)

print(person.school.name)  # Output: KNUST
print(type(person.school))  # Output: <class 'School'>
```

When a dictionary is provided for a nested `BaseModel` field, formax automatically:
1. Detects that the field type is a `BaseModel` subclass
2. Convert the dictionary to an instance of that class
3. Applies all validation rules defined in the nested class

#### Validation Propagation

All validation rules defined in nested models are fully enforced:

```python
from formax import BaseModel, MiniAnnotated, Attrib, validator
from formax.exceptions import ValidationError

class School(BaseModel):
    name: MiniAnnotated[str, Attrib(max_length=50)]
    location: str
    student_count: MiniAnnotated[int, Attrib(gt=0)]
    
    @validator(["name"])
    def validate_name(self, value, field):
        if len(value) < 3:
            raise ValidationError("School name must be at least 3 characters")

class Person(BaseModel):
    name: MiniAnnotated[str, Attrib(max_length=30)]
    age: MiniAnnotated[int, Attrib(gt=0)]
    school: School

# Valid nested validation
person = Person(
    name="Nafiu",
    age=25,
    school={"name": "KNUST", "location": "Kumasi", "student_count": 5000}
)

# Invalid nested validation - will raise ValidationError
try:
    invalid_person = Person(
        name="John",
        age=20,
        school={"name": "AB", "location": "City", "student_count": -10}
    )
except ValidationError as e:
    print(f"Validation failed: {e}")
    # Errors: School name too short, student_count not greater than 0
```

#### Multi-Level Nesting

You can nest models at multiple levels, and validation will propagate through all levels:

```python
class Address(BaseModel):
    street: str
    city: str
    postal_code: MiniAnnotated[str, Attrib(pattern=r"^\d{5}$")]

class School(BaseModel):
    name: str
    address: Address
    principal: str

class Person(BaseModel):
    name: str
    school: School

# Multi-level nested instantiation
person = Person(
    name="Nafiu",
    school={
        "name": "KNUST",
        "principal": "Dr. Smith",
        "address": {
            "street": "University Avenue",
            "city": "Kumasi",
            "postal_code": "12345"
        }
    }
)

print(person.school.address.city)  # Output: Kumasi
```

#### Lists of Nested Models

You can also have collections of nested models:

```python
from typing import List

class Course(BaseModel):
    code: str
    title: str
    credits: MiniAnnotated[int, Attrib(gt=0)]

class Student(BaseModel):
    name: str
    courses: List[Course]

# Instantiate with list of dictionaries
student = Student(
    name="Alice",
    courses=[
        {"code": "CS101", "title": "Intro to Programming", "credits": 3},
        {"code": "CS201", "title": "Data Structures", "credits": 4},
        {"code": "MATH101", "title": "Calculus I", "credits": 3}
    ]
)

# All courses are validated Course instances
for course in student.courses:
    print(f"{course.code}: {course.title} ({course.credits} credits)")
```

#### Non-BaseModel Nested Classes

**Important**: Nested validation only works for `BaseModel` subclasses. If you use a regular Python class or standard dataclass, only the class instance itself is validated, **not** the fields within it.

#### Example with Regular Python Class

```python
# Regular Python class (not BaseModel)
class School:
    def __init__(self, name: str, location: str):
        self.name = name
        self.location = location

class Person(BaseModel):
    name: str
    school: School

# You must pass a School instance - dictionaries won't work
school = School(name="KNUST", location="Kumasi")
person = Person(name="Nafiu", school=school)

# This will FAIL - dictionaries not auto-converted for non-BaseModel classes
try:
    person = Person(
        name="Nafiu",
        school={"name": "KNUST", "location": "Kumasi"}
    )
except TypeError as e:
    print(f"Error: {e}")  # Expected School instance, got dict

# Field validation is NOT applied to School's internal fields
# Only type checking that 'school' is a School instance occurs
school_invalid = School(name="", location="")  # No validation errors!
person = Person(name="Nafiu", school=school_invalid)  # This works!
```

#### Example with Standard Dataclass

```python
from dataclasses import dataclass

# Standard dataclass (not BaseModel)
@dataclass
class School:
    name: str
    location: str

class Person(BaseModel):
    name: str
    school: School

# Must pass School instance
school = School(name="KNUST", location="Kumasi")
person = Person(name="Nafiu", school=school)

# No field validation for School's attributes
# No automatic dictionary conversion
```

## Self References and Forward References

`formax` fully supports self-referential models and forward references. 
Unlike basic dataclasses, it automatically resolves string-based type hints and recursively
inflates nested data into model instances during initialization.

### Recursive Tree Structures

You can define tree-like structures by referencing the class name as a string. These are automatically resolved and validated.

```python
from typing import Optional, List
from formax import BaseModel, MiniAnnotated, Attrib

class TreeNode(BaseModel):
    value: int
    # Self-reference resolved at runtime
    children: MiniAnnotated[List['TreeNode'], Attrib(default_factory=list)]

# Automatic conversion to TreeNode instances
# Nested dictionaries are recursively inflated
root = TreeNode.loads({
    "value": 1, 
    "children": [
        {"value": 2, "children": []}, 
        {"value": 3, "children": [{"value": 4}]}
    ]
}, _format="dict")

assert isinstance(root.children[0], TreeNode)
assert root.children[1].children[0].value == 4
```

### Forward References

Models can reference other models defined later in the same module or in different modules.

```python
class Parent(BaseModel):
    name: str
    # 'Child' is defined below but will be resolved successfully
    first_born: MiniAnnotated["Child", Attrib()]

class Child(BaseModel):
    age: int

# Full validation and inflation even with forward references
p = Parent.loads({"name": "John", "first_born": {"age": 10}}, _format="dict")
assert isinstance(p.first_born, Child)
```

### Optional Nested Models

Nested models can be optional:

```python
from typing import Optional

class ContactInfo(BaseModel):
    email: MiniAnnotated[str, Attrib(pattern=r"^\S+@\S+\.\S+$")]
    phone: str

class Person(BaseModel):
    name: str
    contact: Optional[ContactInfo] # No need to assign = None

# Without contact info
person1 = Person(name="Alice")
print(person1.contact)  # Output: None

# With contact info
person2 = Person(
    name="Bob",
    contact={"email": "bob@example.com", "phone": "+1234567890"}
)
print(person2.contact.email)  # Output: bob@example.com
```

**Note on Optional Fields**: When you annotate a field with typing.Optional, you don't need to explicitly assign None as the default value (i.e., field: `Optional[Type] = None`). The library automatically handles Optional annotations and treats the field as having a None default value. Simply writing field: `Optional[Type]` is sufficient.
```python
from typing import Optional

class User(BaseModel):
    name: str
    # These are equivalent:
    email: Optional[str]           # Automatic None default
    phone: Optional[str] = None    # Explicit None default (redundant but valid)
    
    # Both fields will default to None if not provided
    address: Optional[str]         # Library handles this automatically

# All optional fields default to None
user = User(name="Alice")
print(user.email)    # Output: None
print(user.phone)    # Output: None
print(user.address)  # Output: None
```

### Serialization of Nested Models

Nested models are properly serialized to all supported formats:

```python
class Address(BaseModel):
    city: str
    country: str

class Person(BaseModel):
    name: str
    address: Address

person = Person(
    name="Nafiu",
    address={"city": "Kumasi", "country": "Ghana"}
)

# Serialize to dictionary
person_dict = person.dump(_format="dict")
print(person_dict)
# Output: {'name': 'Nafiu', 'address': {'city': 'Kumasi', 'country': 'Ghana'}}

# Serialize to JSON
person_json = person.dump(_format="json")
print(person_json)
# Output: '{"name": "Nafiu", "address": {"city": "Kumasi", "country": "Ghana"}}'

# Load from JSON with nested validation
loaded_person = Person.loads(person_json, _format="json")
print(type(loaded_person.address))  # Output: <class 'Address'>
```

### Complex Nested Example

Here's a comprehensive example demonstrating nested validation with multiple levels:

```python
from typing import List, Optional
from enum import Enum

class Grade(Enum):
    A = "A"
    B = "B"
    C = "C"
    D = "D"
    F = "F"

class Course(BaseModel):
    code: MiniAnnotated[str, Attrib(pattern=r"^[A-Z]{2,4}\d{3}$")]
    title: MiniAnnotated[str, Attrib(max_length=100)]
    credits: MiniAnnotated[int, Attrib(gt=0, default=3)]
    grade: Optional[Grade] = None
    
    def validate_credits(self, value, field):
        if value > 6:
            raise ValidationError("Course credits cannot exceed 6")
        return value

class Semester(BaseModel):
    year: MiniAnnotated[int, Attrib(gt=2000)]
    term: MiniAnnotated[str, Attrib(pattern=r"^(Fall|Spring|Summer)$")]
    courses: List[Course]
    gpa: MiniAnnotated[float, Attrib(gt=0.0, default=0.0)]
    
    def validate_courses(self, value, field):
        if len(value) > 7:
            raise ValidationError("Cannot enroll in more than 7 courses per semester")
        return value

class Student(BaseModel):
    student_id: MiniAnnotated[str, Attrib(pattern=r"^\d{8}$")]
    name: str
    major: str
    semesters: List[Semester]
    
    def validate_student_id(self, value, field):
        if not value.startswith("20"):
            raise ValidationError("Student ID must start with '20'")
        return value

# Create a student with nested validation at multiple levels
student = Student(
    student_id="20123456",
    name="Nafiu Shaibu",
    major="Computer Science",
    semesters=[
        {
            "year": 2023,
            "term": "Fall",
            "gpa": 3.8,
            "courses": [
                {"code": "CS101", "title": "Intro to Programming", "credits": 3, "grade": "A"},
                {"code": "MATH201", "title": "Calculus II", "credits": 4, "grade": "B"},
                {"code": "ENG101", "title": "English Composition", "credits": 3, "grade": "A"}
            ]
        },
        {
            "year": 2024,
            "term": "Spring",
            "gpa": 3.9,
            "courses": [
                {"code": "CS201", "title": "Data Structures", "credits": 4},
                {"code": "CS221", "title": "Computer Architecture", "credits": 3}
            ]
        }
    ]
)

# Access deeply nested validated data
print(f"Student: {student.name}")
print(f"First semester GPA: {student.semesters[0].gpa}")
print(f"First course: {student.semesters[0].courses[0].title}")

# Serialize with all nested data
student_json = student.dump(_format="json")
# All nested models properly serialized
```

### Best Practices for Nested Validation

1. **Use BaseModel for Nested Classes**: Always inherit from `BaseModel` for nested models to get full validation support
2. **Dictionary Convenience**: Leverage automatic dictionary-to-model conversion for cleaner instantiation code
3. **Validate Early**: Define validation rules at the appropriate level - validate school data in the School model, not in Person
4. **Avoid Deep Nesting**: While supported, excessive nesting (>3-4 levels) can make models hard to maintain
5. **Document Relationships**: Clearly document parent-child relationships in docstrings
6. **Type Hints**: Always use proper type hints for nested fields to enable automatic conversion
7. **Optional Nesting**: Use `Optional[]` for nested models that may not always be present


## Preformatters

Preformatters are callables that transform field values **before** validation occurs. While validators can also transform values, they do so **after** validation has been performed. Preformatters allow you to modify or convert input data into the expected format before any type checking or validation rules are applied.

### When to Use Preformatters

Preformatters are particularly useful for:
- Converting string representations to enum values
- Transforming dictionaries into custom objects
- Normalizing data formats before validation
- Type coercion that needs to happen before type checking
- Conditional transformations based on input type

### Defining a Preformatter

A preformatter is a function that takes a single value argument and returns the transformed value:

```python
def to_pow2(x: int) -> int:
    """Square the input value."""
    return x ** 2
```

Assign the preformatter to the `pre_formatter` argument in `Attrib`:

```python
class MathModel(BaseModel):
    squared_value: MiniAnnotated[int, Attrib(pre_formatter=to_pow2)]

# Usage
model = MathModel(squared_value=5)
print(model.squared_value)  # Output: 25
```

### Execution Order

Understanding the order of operations is crucial:

1. **Preformatter** - Transforms the raw input value
2. **Type Validation** - Checks if the value matches the field's type annotation
3. **Built-in Validators** - Applies Attrib validators (max_length, gt, pattern, etc.)
4. **Custom Validators** - Applies custom validation functions
5. **Method Validators** - Applies validate_<field_name> methods

### Basic Example

```python
from formax import BaseModel, MiniAnnotated, Attrib

def uppercase_formatter(value: str) -> str:
    """Convert string to uppercase before validation."""
    if isinstance(value, str):
        return value.upper()
    return value

class User(BaseModel):
    username: MiniAnnotated[str, Attrib(
        pre_formatter=uppercase_formatter,
        max_length=20
    )]

# The username will be converted to uppercase before validation
user = User(username="john_doe")
print(user.username)  # Output: JOHN_DOE
```

### Enum Resolution Example

A common use case is converting string values to enum instances:

```python
from enum import Enum
from typing import Union
from formax.exceptions import ValidationError

class Status(Enum):
    ACTIVE = "active"
    INACTIVE = "inactive"
    PENDING = "pending"

def resolve_str_to_enum(
    enum_klass: type[Enum], 
    value: str, 
    use_lower_case: bool = False
) -> Union[Enum, str]:
    """Resolve string value to enum instance."""
    if not isinstance(value, str):
        return value
    
    attr_name = value.lower() if use_lower_case else value.upper()
    enum_attr = getattr(enum_klass, attr_name, None)
    
    if enum_attr is None:
        raise ValidationError(
            f"Invalid enum value {value} for {enum_klass.__name__}",
            code="invalid_enum"
        )
    
    return enum_attr

class Task(BaseModel):
    name: str
    status: MiniAnnotated[
        Status,
        Attrib(
            default=Status.PENDING,
            pre_formatter=lambda val: resolve_str_to_enum(
                Status, val, use_lower_case=False
            )
        )
    ]

# Usage - string automatically converted to enum
task = Task(name="Deploy", status="ACTIVE")
print(task.status)  # Output: Status.ACTIVE
print(type(task.status))  # Output: <enum 'Status'>
```

### Dictionary to Model Conversion

Preformatters can convert nested dictionaries into model instances:

```python
class Address(BaseModel):
    street: str
    city: str
    country: str

class Person(BaseModel):
    name: str
    address: MiniAnnotated[
        Address,
        Attrib(
            pre_formatter=lambda val: (
                Address.loads(val, _format="dict")
                if isinstance(val, dict)
                else val
            )
        )
    ]

# Automatically converts dictionary to Address instance
person = Person(
    name="Alice",
    address={"street": "123 Main St", "city": "New York", "country": "USA"}
)

print(person.address.city)  # Output: New York
```

### Complex Example from Volnux

Here's a real-world example from the [Volnux](https://github.com/nshaibu/volnux) project demonstrating advanced preformatter usage:

```python
import typing
from enum import Enum
from dataclasses import dataclasses

class ResultEvaluationStrategy(Enum):
    ALL_MUST_SUCCEED = "all_must_succeed"
    ANY_MUST_SUCCEED = "any_must_succeed"

class StopCondition(Enum):
    ON_FIRST_SUCCESS = "on_first_success"
    ON_FIRST_FAILURE = "on_first_failure"

class ExecutorInitializerConfig(BaseModel):
    max_workers: int = 4
    thread_name_prefix: str = "Executor"

def resolve_str_to_enum(
    enum_klass: typing.Type[Enum], 
    value: str, 
    use_lower_case: bool = False
) -> typing.Union[Enum, str]:
    """Resolve enum value to enum class."""
    if not isinstance(value, str):
        return value
    
    attr_name = value.lower() if use_lower_case else value.upper()
    enum_attr = getattr(enum_klass, attr_name, None)
    
    if enum_attr is None:
        raise ValidationError(
            f"Invalid enum value {value} for {enum_klass.__name__}", 
            code="invalid_enum"
        )
    
    return enum_attr

class Options(BaseModel):
    """
    Task execution configuration options that can be passed to a task or
    task groups in pointy scripts, e.g., A[retry_attempts=3], {A->B}[retry_attempts=3].
    """
    
    # Core execution options with validation
    retry_attempts: MiniAnnotated[int, Attrib(default=0, ge=0)]
    executor: MiniAnnotated[typing.Optional[str], Attrib(default=None)]
    
    # Configuration dictionaries with preformatter
    executor_config: MiniAnnotated[
        typing.Union[ExecutorInitializerConfig, dict],
        Attrib(
            default_factory=lambda: ExecutorInitializerConfig(),
            pre_formatter=lambda val: (
                ExecutorInitializerConfig.from_dict(val)
                if isinstance(val, dict)
                else val
            ),
        ),
    ]
    extras: MiniAnnotated[dict, Attrib(default_factory=dict)]
    
    # Execution state and control with enum preformatters
    result_evaluation_strategy: MiniAnnotated[
        ResultEvaluationStrategy,
        Attrib(
            default=ResultEvaluationStrategy.ALL_MUST_SUCCEED,
            pre_formatter=lambda val: resolve_str_to_enum(
                ResultEvaluationStrategy, val, use_lower_case=False
            ),
        ),
    ]
    stop_condition: MiniAnnotated[
        typing.Union[StopCondition, None],
        Attrib(
            default=None,
            pre_formatter=lambda val: val
            and resolve_str_to_enum(StopCondition, val, use_lower_case=False)
            or None,
        ),
    ]
    bypass_event_checks: typing.Optional[bool]
    
    class Config:
        disable_typecheck = False
        disable_all_validation = False
    
    @classmethod
    def from_dict(cls, options_dict: typing.Dict[str, typing.Any]) -> "Options":
        """
        Create Options instance from dictionary, placing unknown fields in extras.
        
        Args:
            options_dict: Dictionary containing option values
            
        Returns:
            Options instance with known fields populated and unknown fields in extras
        """
        known_fields = {field.name for field in dataclasses.fields(cls)}
        
        option = {}
        for field_name, value in options_dict.items():
            if field_name in known_fields:
                option[field_name] = value
            else:
                # Place unknown fields in extras
                if "extras" not in option:
                    option["extras"] = {}
                option["extras"][field_name] = value
        
        return cls.loads(option, _format="dict")

# Usage example
options = Options(
    retry_attempts=3,
    executor_config={"max_workers": 8, "thread_name_prefix": "Worker"},
    result_evaluation_strategy="ALL_MUST_SUCCEED",  # String converted to enum
    stop_condition="ON_FIRST_FAILURE"  # String converted to enum
)

print(options.executor_config.max_workers)  # Output: 8
print(options.result_evaluation_strategy)  # Output: ResultEvaluationStrategy.ALL_MUST_SUCCEED
```

### Best Practices

1. **Type Checking**: Always check the input type before transformation to handle various input formats gracefully
2. **Error Handling**: Raise `ValidationError` for invalid transformations that cannot be resolved
3. **Idempotency**: Ensure preformatters can handle already-transformed values (e.g., enum already being an enum)
4. **Lambda Functions**: Use lambda functions for simple, inline transformations
5. **Dedicated Functions**: Create dedicated functions for complex or reusable transformation logic

### Preformatter vs Validator

| Aspect | Preformatter | Validator |
|--------|-------------|-----------|
| Execution timing | Before validation | After validation |
| Primary purpose | Data transformation | Data validation |
| Type checking | Happens after | Already completed |
| Use case | Format conversion | Business rule enforcement |
| Return value | Transformed value | Validated/transformed value |

### Combined Example

Preformatters and validators work together seamlessly:

```python
def strip_whitespace(value: str) -> str:
    """Preformatter: Remove leading/trailing whitespace."""
    if isinstance(value, str):
        return value.strip()
    return value

def validate_no_numbers(instance, value: str) -> str:
    """Validator: Ensure no digits in string."""
    if any(char.isdigit() for char in value):
        raise ValidationError("Value cannot contain numbers")
    return value

class CleanModel(BaseModel):
    clean_text: MiniAnnotated[
        str,
        Attrib(
            pre_formatter=strip_whitespace,
            validators=[validate_no_numbers],
            max_length=50
        )
    ]

# Execution order:
# 1. Preformatter strips whitespace: "  hello  " → "hello"
# 2. Type validation: Check if string
# 3. Built-in validator: Check max_length
# 4. Custom validator: Check for numbers

model = CleanModel(clean_text="  hello world  ")
print(model.clean_text)  # Output: "hello world"
```

## Serialization

### Supported Formats

Formax supports three serialization formats:

#### JSON
```python
person = Person(name="John", age=30)

# Serialize to JSON
json_str = person.dump(_format="json")
print(json_str)  # '{"name": "John", "age": 30}'

# Deserialize from JSON
person = Person.loads('{"name": "Alice", "age": 25}', _format="json")
```

#### Dictionary
```python
# Serialize to dictionary
person_dict = person.dump(_format="dict")
print(person_dict)  # {'name': 'John', 'age': 30}

# Deserialize from dictionary
person = Person.loads({"name": "Bob", "age": 35}, _format="dict")
```

#### CSV
```python
# Deserialize from CSV (returns list of instances)
csv_data = "name,age\nJohn,30\nAlice,25\nBob,35"
people = Person.loads(csv_data, _format="csv")

for person in people:
    print(person)
```

## Model Formatters

Model formatters in formax define how a model is loaded from and dumped to
external representations such as `JSON`, `dicts`, `CSV`, or custom formats like `YAML` or `TOML`.

They operate at the model boundary and are responsible for full-model serialization and deserialization.

Model formatters are used by:

```
BaseModel.loads(data, _format=...) → decode / read

BaseModel.dump(_format=...) → encode / write
```

### Custom Formatters

To create a custom formatter, you need to inherit from `BaseModelFormatter` and implement the `encode` (reading data) and `decode` (writing data) methods.

#### Formatter Base Classes

##### BaseModelFormatter
- Low-level base class for custom formats
- Use only for non-dict-like formats or full control

##### DictModelFormatter (recommended)
- Handles recursive model inflation and nested BaseModel instances
- Supports lists and primitive type handling
- You only need to convert external format ↔ dict/list

#### Required Interface
`format_name`
```python
format_name = "yaml"
# or with aliases
format_name = ("yaml", "yml")
```
- Matched against the _format parameter

`encode(self, _type, obj)`
- Used when loading data into a model
- `_type`: target BaseModel class
- `obj`: raw external input (usually string)
- Returns dict/list suitable for model inflation

`decode(self, instance)`
- Used when dumping a model
- `instance`: BaseModel instance or nested data
- Returns serialized output (usually string)

#### Example
#### 1. Creating a YAML Formatter

Here is an example of how to add YAML support using the `PyYAML` library.

```python
import yaml
from typing import Type, Any
from formax.formatters import BaseModelFormatter, DictModelFormatter

class YAMLModelFormatter(DictModelFormatter):
    """
    A custom formatter for YAML support.
    Inheriting from DictModelFormatter allows us to reuse 
    the dictionary-to-model logic.
    """
    format_name = "yaml"

    def encode(self, _type: Type["BaseModel"], obj: str) -> Any:
        # Convert YAML string to dict
        data = yaml.safe_load(obj)
        # Leverage DictModelFormatter logic to inflate models
        return super().encode(_type, data)

    def decode(self, instance: Any) -> str:
        # Leverage DictModelFormatter to get a raw dict/list
        data = super().decode(instance)
        # Convert dict to YAML string
        return yaml.dump(data)
```

#### 2. Using the Custom Formatter

Once the class is defined, it is automatically registered. You can use it via the standard `.loads()` and `.dump()` methods on any `BaseModel`.

```python
class Task(BaseModel):
    name: str
    priority: int

yaml_data = """
name: "System Update"
priority: 1
"""

# The library finds 'YAMLModelFormatter' via the 'yaml' key
task = Task.loads(yaml_data, _format="yaml")
print(task.name) # Output: System Update

# Exporting back to YAML
print(task.dump(_format="yaml"))
```

#### 3. Implementation Guidelines

1. **Discovery**: As long as your formatter is imported in your runtime, it will be available.

2. **DictModelFormatter as a Base**: It is highly recommended to inherit from `DictModelFormatter` rather than the raw BaseModelFormatter. This allows you to focus only on the string-to-dict conversion while the base class handles the complex recursive model inflation.

3. **The format_name**: This string is the key used in the `_format` parameter. You can also provide a list or tuple of names if you want to support aliases (e.g., format_name = ("yaml", "yml")).

## Configuration

### Model Configuration

Configure model behavior using the `Config` class:

```python
import os
from datetime import datetime
import typing

class EventResult(BaseModel):
    error: bool
    task_id: str
    event_name: str
    content: typing.Any
    init_params: typing.Optional[typing.Dict[str, typing.Any]]
    call_params: typing.Optional[typing.Dict[str, typing.Any]]
    process_id: MiniAnnotated[int, Attrib(default_factory=lambda: os.getpid())]
    creation_time: MiniAnnotated[float, Attrib(default_factory=lambda: datetime.now().timestamp())]
    
    class Config:
        unsafe_hash = False
        frozen = False
        eq = True
        order = False
        disable_typecheck = False
        disable_all_validation = False
```

### Configuration Options

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `init` | `bool` | `True` | Whether the `__init__` method is generated for the dataclass |
| `repr` | `bool` | `True` | Whether a `__repr__` method is generated |
| `eq` | `bool` | `True` | Enables the generation of `__eq__` for comparisons |
| `order` | `bool` | `False` | Enables ordering methods (`__lt__`, `__gt__`, etc.) |
| `unsafe_hash` | `bool` | `False` | Allows an unsafe implementation of `__hash__` |
| `frozen` | `bool` | `False` | Makes the dataclass instances immutable |
| `strict_mode` | `bool` | `False` | Disable or enable automatic type coercion |
| `disable_typecheck` | `bool` | `False` | Disable runtime type checking in models |
| `disable_all_validation` | `bool` | `False` | Disable all validation logic (type + custom rules) |

## Advanced Usage

### Using InitVar

For fields that are only used during initialization:

```python
from dataclasses import InitVar
import typing

class DatabaseRecord(BaseModel):
    id: int
    name: str
    database: InitVar[typing.Optional[object]] = None
    
    def __model_init__(self, database):
        if database is not None and self.id is None:
            self.id = database.get_next_id()
```

### Default Factories

Use `default_factory` for dynamic default values:

```python
import uuid
from datetime import datetime

class Task(BaseModel):
    id: MiniAnnotated[str, Attrib(default_factory=lambda: str(uuid.uuid4()))]
    created_at: MiniAnnotated[float, Attrib(default_factory=lambda: datetime.now().timestamp())]
    title: str
    completed: MiniAnnotated[bool, Attrib(default=False)]
```

### Simple ORM Usage

Create lightweight ORMs for in-memory data management:

```python
class PersonORM:
    def __init__(self):
        self.people_db = []
    
    def create(self, **kwargs):
        person = Person(**kwargs)
        self.people_db.append(person)
        return person
    
    def find_by_age(self, min_age):
        return [p for p in self.people_db if p.age >= min_age]
    
    def find_by_name(self, name):
        return [p for p in self.people_db if p.name == name]

# Usage
orm = PersonORM()
orm.create(name="John", age=30)
orm.create(name="Alice", age=25)
orm.create(name="Bob", age=35)

adults = orm.find_by_age(18)
johns = orm.find_by_name("John")
```

## Examples

### Complete User Management Example

```python
import re
from typing import Optional, List
from formax import BaseModel, MiniAnnotated, Attrib
from formax.exceptions import ValidationError

def validate_strong_password(instance, password: str):
    """Validate password strength."""
    if len(password) < 8:
        raise ValidationError("Password must be at least 8 characters long")
    if not re.search(r"[A-Z]", password):
        raise ValidationError("Password must contain at least one uppercase letter")
    if not re.search(r"[a-z]", password):
        raise ValidationError("Password must contain at least one lowercase letter")
    if not re.search(r"\d", password):
        raise ValidationError("Password must contain at least one digit")
    return password

def validate_username(instance, username: str):
    """Validate username format."""
    if not re.match(r"^[a-zA-Z0-9_]+$", username):
        raise ValidationError("Username can only contain letters, numbers, and underscores")
    return username.lower()

class User(BaseModel):
    username: MiniAnnotated[str, Attrib(
        max_length=30, 
        validators=[validate_username]
    )]
    email: MiniAnnotated[str, Attrib(
        pattern=r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
    )]
    password: MiniAnnotated[str, Attrib(validators=[validate_strong_password])]
    age: MiniAnnotated[int, Attrib(gt=13, default=18)]
    is_active: MiniAnnotated[bool, Attrib(default=True)]
    roles: Optional[List[str]] = None
    
    def validate_age(self, value, field):
        if value > 120:
            raise ValidationError("Age seems unrealistic")
        return value
    
    class Config:
        frozen = False
        eq = True

# Usage example
try:
    user = User(
        username="JohnDoe123",
        email="john@example.com",
        password="SecurePass123",
        age=25,
        roles=["user", "admin"]
    )
    
    # Serialize user
    user_json = user.dump(_format="json")
    print("User JSON:", user_json)
    
    # Load from JSON
    loaded_user = User.loads(user_json, _format="json")
    print("Loaded user:", loaded_user)
    
except ValidationError as e:
    print(f"Validation error: {e}")
```

### E-commerce Product Example

```python
from decimal import Decimal
from typing import Optional, List
from enum import Enum

class ProductStatus(Enum):
    ACTIVE = "active"
    INACTIVE = "inactive"
    DISCONTINUED = "discontinued"

def validate_price(instance, price: float):
    if price < 0:
        raise ValidationError("Price cannot be negative")
    if price > 1000000:
        raise ValidationError("Price too high")
    return round(price, 2)

def validate_sku(instance, sku: str):
    if not re.match(r"^[A-Z]{2,3}-\d{4,6}$", sku):
        raise ValidationError("SKU must be in format XX-NNNN or XXX-NNNNNN")
    return sku.upper()

class Product(BaseModel):
    name: MiniAnnotated[str, Attrib(max_length=100)]
    sku: MiniAnnotated[str, Attrib(validators=[validate_sku])]
    price: MiniAnnotated[float, Attrib(validators=[validate_price])]
    description: Optional[str] = None
    category: str
    tags: Optional[List[str]] = None
    stock_quantity: MiniAnnotated[int, Attrib(default=0)]
    status: str = ProductStatus.ACTIVE.value
    
    def validate_stock_quantity(self, value, field):
        if value < 0:
            raise ValidationError("Stock quantity cannot be negative")
        return value
    
    def validate_category(self, value, field):
        valid_categories = ["electronics", "clothing", "books", "home", "sports"]
        if value.lower() not in valid_categories:
            raise ValidationError(f"Category must be one of: {valid_categories}")
        return value.lower()

# Create products
products = [
    Product(
        name="Wireless Headphones",
        sku="EL-1234",
        price=99.99,
        description="High-quality wireless headphones",
        category="electronics",
        tags=["wireless", "audio", "bluetooth"],
        stock_quantity=50
    ),
    Product(
        name="Python Programming Book",
        sku="BK-5678",
        price=29.99,
        category="books",
        stock_quantity=25
    )
]

# Serialize to JSON
products_json = [p.dump(_format="json") for p in products]
print("Products JSON:", products_json)
```

## Error Handling

### ValidationError

All validation failures raise `ValidationError`:

```python
from formax.exceptions import ValidationError

try:
    user = User(username="", email="invalid-email", age=-5)
except ValidationError as e:
    print(f"Validation failed: {e}")
    # Handle the error appropriately
```

### Best Practices for Error Handling

```python
def create_user_safely(user_data):
    try:
        user = User.loads(user_data, _format="dict")
        return {"success": True, "user": user}
    except ValidationError as e:
        return {"success": False, "error": str(e)}
    except Exception as e:
        return {"success": False, "error": f"Unexpected error: {e}"}

# Usage
result = create_user_safely({
    "username": "testuser",
    "email": "test@example.com",
    "password": "SecurePass123"
})

if result["success"]:
    print("User created:", result["user"])
else:
    print("Error:", result["error"])
```

## Performance Considerations

### Disabling Validation

For performance-critical scenarios, you can disable validation:

```python
class FastModel(BaseModel):
    field1: str
    field2: int
    
    class Config:
        disable_typecheck = True
        disable_all_validation = True
```

### Efficient Serialization

Choose the appropriate serialization format based on your needs:
- Use `dict` format for Python-to-Python communication
- Use `json` format for API responses and storage
- Use `csv` format for data export and reporting

## Contributing

Contributions are welcome! To contribute to formax:

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Ensure all tests pass
6. Submit a pull request

### Development Setup

```bash
git clone https://github.com/nshaibu/formax.git
cd formax
# Set up your development environment
# Run tests
python -m pytest tests/
```

### Code Style

- Follow PEP 8 style guidelines
- Use type hints for all functions and methods
- Add docstrings for public APIs
- Write comprehensive tests for new features

## License

Formax is open-source and available under the GPL License.

## Changelog

### Future Releases
- Additional built-in validators
- Performance optimisations
- Extended serialisation formats

---

