Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8304789
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T17:56:11+00:00 2026-06-08T17:56:11+00:00

Short, but complete, summary I want to allow users of my function (a class

  • 0

Short, but complete, summary

I want to allow users of my function (a class factory) to inject/overwrite global imports when using my function (longer explanation of rationale below). But there are about 10 different variables that could be passed in and it adds a number of very repetitive lines to the code. (granted, also makes it more complicated to call too :P) Right now, I’m doing something like the following (just simplifying all of this). To make it runnable, I’m using a dummy class, but in the actual script I’d be using import pkg1, etc. Figured this was clearer and shorter than a class factory, etc.

class Dummy(object): pass

pkg1, pkg2 = Dummy(), Dummy()
pkg1.average = lambda *args : sum(args) / len(args)
pkg2.get_lengths = lambda *args : map(len, args)


def get_average(*args, **kwargs):
    average = kwargs.get("average") or pkg1.average
    get_lengths = kwargs.get("get_lengths") or pkg2.get_lengths
    return average(*get_lengths(*args))

adjusted_length = lambda *args: map(len, args) + [15]
print get_average([1,2], [10, 4, 5, 6]) == 3 # True
print get_average([1,2], [10, 4, 5, 6], get_lengths=adjusted_length) == 7 # True

Related SO questions

This stack overflow post: Modifying locals in Python, seemed particularly relevant and initially I wanted to just overwrite locals by storing to the locals dictionary but (1) it didn’t seem to work, and (2) it seems like it was a bad idea. So, I’m wondering if there’s another way to do it.

This one looked promising ( Adding an object to another module's globals in python ), but I’m not really sure how to access the globals for the current file in the same way as a module. (and this question – python: mutating `globals` to dynamically put things in scope – doesn’t really apply, since I’m (ultimately) using this to define classes).

I guess I could wrap everything in an exec statement (like this post – globals and locals in python exec() ), but that’s both fiddly and means that it’s much harder to do error checking/linting/etc.

So here’s what I’d like to do. (NOTE: I would have used from pkg1 import average AND from pkg2 import get_lengths
but I wanted the example to be clearer (need to copy pkg1 and pkg2 above to run this))

average = pkg1.average
get_lengths = pkg2.get_lengths

def get_average(*args, **kwargs):
    localvars = locals()
    for k in ("get_lengths", "average"):
        if kwargs.get(k, None) and kwargs[k] is not None:
            localvars[k] = kwargs[k]
    return average(*get_lengths(*args))

print get_average([1,2], [10, 4, 5, 6]) == 3 #True
print get_average([1,2], [10, 4, 5, 6], get_lengths=adjusted_length) == 7 # False, is 3

Rationale for my specific use-case

Right now, I’m trying to write a dynamically-generated class factory (to use as an SQLAlchemy mixin), but I want to allow users of my class to pass in alternate constructors, so they can use SQLAlchemy adapters, etc.

For example, Flask-SQLAlchemy provides the same interface as SQLAlchemy, but provides a custom object/class (db) that wraps around all the SQLAlchemy objects to provide more features.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T17:56:13+00:00Added an answer on June 8, 2026 at 5:56 pm

    You could use arguments with default values to pass functions in. This is effectively what you are doing but cleaner. I’ve used lists as a single argument instead of *args because it is easier to deal with when you have other arguments. You’ll have to enclose your lists in a tuple to pass them in to get_average.

    The builtin function sorted works like this so it should be easy for Python programmers to understand.

    get_average(lists, average=pkg1.average, get_lengths=pkg2.get_lengths):
        return average(*get_lengths(*lists))
    
    print get_average(([1,2], [10, 4, 5, 6]))
    print get_average(([1,2], [10, 4, 5, 6]), get_lengths=adjusted_length)
    

    If you have many keyword arguments you could package them in an object:

    class GetAverageContext(object):
        def __init__(self, average=pkg1.average, get_lengths=pkg2.get_lengths):
            self.average = average
            self.get_lengths = get_lengths
    
    DefaultGetAverageContext = GetAverageContext()
    
    def get_average(lists, context=DefaultGetAverageContext):
        return context.average(*context.get_lengths(*lists))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

The code is short,but complete : function process($obj) { if(empty($obj))return 1; return 2; }
I want to make a short URL service for 2 million assets but I
In short: For this code: Encoding.ASCII.GetBytes(‚) I want the output to be 130, but
I've read how to do this but I'm falling short on implementation. I want
I'm using AWS' SimpleDB as intended for the most part, but also want to
I've tried short text answers but they still wrap to a new line instead
I know that E is short for 'event,' but it's still not clear to
This is a really short question I think but I'm not sure I understand
Short story: stopPropagation() prevents a dropdown menu from closing - which is good. But
Short problem description: XCode 4.2 install right Target on device, but debug (run) always

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.