1

I have a depth first search algorithm that is pulling information from an Ontology.

I have a working function to get all of the objects with a particular property, however, I essentially need to do the same thing for a different property.

If I have these two simplified functions for example

def a():
    for n in nodes:
        do something with n.property1

def b():
    for n in nodes:
        do something with n.property2

Is there a way that I can pass the desired property in as a parameter? So that I end up with:

def a(property):
    for n in nodes:
        do something with n.property

a(property1)
a(property2)

2 Answers 2

2

Technically, yes. getattr() is a built-in function that allows you to get a property from an object based on its name. setattr() also exists, and can be used to assign a value to a property from an object based on the property's name.

def a(propertyname):  # pass property name as a string
    for n in nodes:
        do something with getattr(n, propertyname)

a('property1')
a('property2')

However, this is generally considered a bit risky, and it's probably better to structure your code in such a way that it's not necessary. It might be possible, for example, to use lambdas instead:

def a(getter):
    # pass a function that returns the value of the relevant parameter
    for n in nodes:
        do something with getter()

a(lambda n:n.property1)
b(lambda n:n.property2)
Sign up to request clarification or add additional context in comments.

3 Comments

Can you elaborate on why this is considered risky?
@SeanPayne mostly because it makes it easier to mess with your objects unintentionally (e.g. by changing the variable passed to it arbitrarily), but also because it's a little more difficult for static code tools to understand than the usual obj.property syntax. Not necessarily bad (and I was wrong to put as such in my answer, I'll change that), but you should definitely know what you're doing before using getattr() lest it lead to mistakes that are hard to debug.
Thank you, that makes sense. I will use it as there is very low risk of having these types of problems in the project I'm currently working on.
1

You can do the following:

def a(property):
   ...
   print(getattr(n, property))

and call this method with string parameters:

a("property1")
a("property2")

Comments

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.