0

Relatively new to python, coming from C#, so bear with me :)

Basically I got a ton of "nearly-duplicated" SQLAlchemy code that looks like so ...

def method1():    
    dbObj1 = Class1.query.filter_by(id=search_id).first()
    [a bunch of operations on this object]

....

def method2():
    dbObj2 = Class2.query.filter_by(id=search_id).first()
    [the same operations on this object]

The operations performed on these objects are the same and access properties that exist in both these classes. In C# or Java I'd solve that by having some sort of base class and/or using generics. However I have no clue how one would solve such duplication problems in Python.

Is there anything similar to generics? Or maybe that SQLAlchemy query could be changed in some way so these occurrences can be deduplicated?

Thanks for any inputs :)

EDIT: made the example a little more clear

3
  • 1
    Classes are, themselves, objects so you can do for class_name in (Class1, Class2): class_name.query.filter..... Commented Feb 10, 2020 at 10:12
  • @FiddleStix well it's in different methods, not right after each other :D But I guess that also means I could have something like doOperationsOn(Class1), right? Commented Feb 10, 2020 at 10:14
  • Can you post the actual code here? Commented Feb 10, 2020 at 10:14

1 Answer 1

1

You can actually just pass the class like this:

class A:
        def foo(self):
                return "foo"

class B: 
        def foo(self):
                return "bar"

def do_something(c):
        e = c()
        print(e.foo())


do_something(A)
do_something(B)
Sign up to request clarification or add additional context in comments.

3 Comments

Passing the class is fine, but OP wants to use a class (or static) attribute later, so no need of creating an instance.
Didn't know that, that looks exactly like what I need. @SergeBallesta I guess it was just for examples sake to show creation of an instance with the passed class ;)
@SergeBallesta I'm aware ... but there is a minimum time limit before you can accept an answer ... so I got to sit that one out ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.