I’m trying to create a think proxy using the __get__ descriptor over a certain type of data so that it can be used conveniently by client code (best shown with an example):
class Value(object):
def __init__(self, val):
self.val = val
def __get__(self, instance, owner):
return self.val
class Container(object):
x = Value(1)
y = [ Value(2), Value(3) ]
c = Container()
assert c.x == 1
assert c.y[0] == 2 # fails.
Now, I mostly see why it fails, so I’m wondering if theres a better way to achieve my goal which is wrap up the data so that when the client accesses it they simply have to access the Value object directly (in reality, the __get__ method would do something with self.val before returning it)
Details
The actual case I’m trying to tackle is utility code to assist in writing PageObjects & PageElements for selenium test cases. What I want to provide is a clean and simple way for test authors to write PageObjects of the form:
class MyLogin(PageObject):
username_text_box = PageElement(By.ID, "username")
password_text_box = PageElement(By.ID, "password")
submit_button = PageElement(By.CLASS_NAME, "login-button")
driver = webdriver.Firefox()
driver.get("http://mypage.com")
login_page = MyLogin(driver)
login_page.username_text_box.send_keys("username01")
login_page.password_text_box.send_keys("XXXX")
login_page.submit_button.click()
I’m trying to encapsulate the business of fetching the actual WebElement inside the PageElement class and I want to allow the client to have access to the WebElement once they access the PageElement Object. Being able to have lists, dictionaries assists in making the PageObject instance clearer and to group related PageElements.
I settled with an implementation which both jsbueno & python_noob were approaching. However both their implementations don’t meet my criteria of allowing test authors to write simple declarative page object.