Is it bad practice to put stuff into new function properties?
<p>Say I have a class and a function:</p>

<pre><code>class AddressValidator(self):
    def __init__(self):
        pass
    def validate(address):
        # ...

def validate_address(addr):
    validator = AddressValidator()
    return validator.validate(addr)
</code></pre>

<p>The function is a shortcut for using the class, if you will. Now, what if this function has to be run thousands of times? If the validator class actually has to do something on instantiation, like connecting to a database, creating it over and over thousands of times is pretty wasteful. I was wondering if I could perhaps do something like this:</p>

<pre><code>def validate_address(addr):
    if not hasattr(validate_address, 'validator'):
        validate_address.validator = AddressValidator()

    validator = validate_address.validator
    return validator.validate(addr)
</code></pre>

<p>Now the validator class is only instantiated once and saved "in the function", to put it that way. I've never seen this done though, so I'm guessing it's bad practice. If so, why?</p>

<p><em>Note: I know I can just cache the validator object in a module global. I'm just curious if this is a viable solution when I want to avoid littering my module.</em></p>
