python list comprehension

Python list or other comprehension has the following syntax

{key_expr: value_expr for item in iterable if condition}


So let's look at an example here, that allow us to get only property

 


import inspect

class Employee:
    name: str
    id: int

    def __init__(self, ename:str, eid:int):
     self.name = ename
     self.id = eid

    def hello(_self):
     print("employee")

    @property
    def email(self):
     return "kepung@gmail.com"

e = Employee("Alice", 2)

properties = [name for name, value in inspect.getmembers(type(e))
              if isinstance(value, property)]
print("Properties:", properties)


You can see here that we're trying to get name only. 

Running inspect.getmembers(type(e)) would return name and value. Then we have an if statement there that will check isinstance property.



# Get all properties
properties = [name for name, value in inspect.getmembers(type(e))
              if isinstance(value, property)]
print("Properties:", properties)




Comments

Popular posts from this blog

gemini cli getting file not defined error

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20

vllm : Failed to infer device type