Robin Lin
Robin Lin

Reputation: 11

Can modules have properties the same way that objects can?

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.

Upvotes: 0

Views: 32

Answers (1)

Daweo
Daweo

Reputation: 36660

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

Upvotes: 1

Related Questions