0

As the Q&A Can modules have properties the same way that objects can?

But I just want to use y as module.y, so I run

module.py

import time
def __getattr__(name):
    if name == 'y':
        return time.time()
    raise AttributeError(f"module '{__name__}' has no attribute '{name}'")

main.py

import time
from module import y
x = time.time()
print(x)
time.sleep(1)
print(y)
time.sleep(1)
print(y)

But the result of y won't change, It always equals to x. How to solve the problem?

I expect y always return the current time.

Robin Lin
  • 11
  • 2
  • 1
    `__getattr__` isn’t re-run every time you `print(y)`. You already got `y` once and saved it to a name. Only an *attribute access* evaluates the getter. – deceze Dec 29 '22 at 07:16
  • you could set y to `time.time` and then call `print(y())` to get the behavior you want – WombatPM Dec 29 '22 at 07:30

1 Answers1

1

You might use external package mprop to get desired effect, following way

mod.py

import time
from mprop import mproperty

@mproperty
def y(mod):
    return time.time()

main.py

import mod
import time

t1 = mod.y
time.sleep(1)
t2 = mod.y
time.sleep(1)
t3 = mod.y

print(t3-t2, t2-t1)

output of python main.py

1.0011167526245117 1.0011308193206787
Daweo
  • 31,313
  • 3
  • 12
  • 25