Better introspection for callable `default`

Issue #2520 resolved
George Sakkis created an issue

I've been caught by surprise more than once by the fact that a callable default is interpreted differently depending on whether its signature accepts zero or more than zero parameters; in the second case it is assumed to be a context-sensitive default function and it is called by passing the context. This assumption fails for callables that take parameters but they are all optional. The current workaround is to wrap the function in a parameterless lambda but it shouldn't be hard to tweak the introspection so that callables with only optional parameters are called without parameters (i.e. not passing context).

Comments (7)

  1. Mike Bayer repo owner
    • changed milestone to 0.8.0

    right but that would break backwards compatibility if someone is using it with a callable like def my_default(context=None). What's the use case for passing a callable that isn't exactly my_default() or my_default(ctx) ? if anything the introspection should just raise if it isn't exactly those signatures (guess it is).

  2. George Sakkis reporter

    Don't context-sensitive functions require the context? Can't think of why would one define my_default(context=None).

    Use case is callables that weren't defined specifically to be used as column defaults, they are used in other places with their non default values. For example:

    def random_token(min_length=64, max_length=64, alphabet=string.letters + string.digits):
        """Generate a random token"""
    
    ...
        access_token = Column(Unicode(64), default=random_token)
    
  3. Mike Bayer repo owner

    Yeah I think that usage of random_token should be wrapped. Ideally the callable passed to default would have exactly one signature, but because usage of context is such the rare case we have the introspection thing happening.

  4. George Sakkis reporter

    Indeed it would be better if introspection was avoided but given that it is happening, I don't really see the harm in supporting better the common case (context-less callable). I could whip up a patch if it makes a difference.

  5. Log in to comment