Reputation: 351
I want to call a function that takes a class as an argument, without passing it a class.
The function only uses an integer value from the class, and the place I call it from has information that can calculate the value independently.
My code looks like:
Function I want to call:
def buckets_from_pairs(fs_pairs,par):
fsea=fermi_sea(par.N)
# rest of function has no reference to par
Function I call from:
def deltas(roots):
if "buckets" in roots:
# do function on roots["buckets"]
if "partition" in roots:
#somehow define value such that value.N=len(roots["roots"])
buckets=buckets_from_pairs(roots["partition"], value)
#do function on buckets
I could change deltas
to take par
as an argument and I could change buckets_from_pairs
to work without par
but both would require a lot of reworking, and I would have to organise it with my supervisor who wrote both functions (he doesn't have this problem).
So I was hoping there was a simpler way of creating an object that can use the "dot" to reference something than creating a new class in the calling function.
Upvotes: 0
Views: 129
Reputation: 414615
If the value should be modifiable; you could use types.SimpleNamespace class in Python 3.3+:
from types import SimpleNamespace
value = SimpleNamespace(N=len(roots["roots"]))
On older Python versions you could use Adapter class.
For read-only case; you could use namedtuple
.
Upvotes: 1
Reputation: 5046
@gnibbler answer is good and @John Zwinck had a good idea, but it can be made general:
class objval(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
par = objval(N=len(roots["roots"])
In general, objval
allows you to create values wrapped in objects on the fly like:
o = objval(prop1=value1, prop2=value2)
Your choice of solution comes down to a matter of taste.
Upvotes: 1
Reputation: 304355
from collections import namedtuple
value = namedtuple('Value', 'N')(len(roots["roots"]))
Upvotes: 4
Reputation: 249424
You can make a little adapter like this:
class Adapter(object):
def __init__(self, n):
self.N = n
Then:
buckets=buckets_from_pairs(roots["partition"], Adapter(len(roots["roots"]))
Upvotes: 4
Reputation: 20373
Why not just
def buckets_from_pairs(fs_pairs, N):
fsea=fermi_sea(N)
called with
buckets=buckets_from_pairs(roots["partition"], value.N)
Upvotes: 2