4

In Python 3, I made a custom class C for a specific data structure that can be used as an iterable.

But the class ensures that for any data structure c of C, c[0] will be the minimum value of all values in c.

Is there a way that a call to min(c) simply returns c[0] without uselessly exploring all the structure ? (or as usual a ValueError if c is empty)

Xoff
  • 356
  • 2
  • 13

1 Answers1

2

Is there a way that a call to min(c) simply returns c[0]?

Yes, there is 2 way :

The first one is modifying the source code of python and change the built in function structure, which is not wise and rational at all.

The second way is create your own min function in relative namespace.

Actually based on python name-resolution scheme which called the LEGB manner, When you use an unqualified name inside a scope, Python searches up to four scopes, the local (L) scope, then the local scopes of any enclosing (E) scopes (if it exist) , then the global (G) scope, and then the built-in (B) scope.Thus due to this rule the built in scope will be searches at end and you can simply create a new one on top level of this scope.

But Note that in that case you couldn't use the preceding min function, and if it happens to use it you can delete the costume function using del statement.

But another pythonic way to go with this task is that creating a min function inside your class and use it as an attribute :

>>> class C(object):
...    def __init__(self):
...        self.index = 0
...        self.iterable = range(10)
...    def __iter__(self):
...        return self
...    def min(self):
...      try:
...          return self.iterable[self.index]
...      except IndxError:
...          raise Exception('The index is out of range')
>>> c=C()
>>> 
>>> c.min()
0
>>> c.iterable=[5,1,4,8]
>>> c.min()
5

Note that in this case you can specify a default index for min function to returns the relative item.

Community
  • 1
  • 1
Mazdak
  • 105,000
  • 18
  • 159
  • 188