Coder Social home page Coder Social logo

avilum / linqit Goto Github PK

View Code? Open in Web Editor NEW
245.0 13.0 14.0 75 KB

Extend python lists operations using .NET's LINQ syntax for clean and fast coding.

License: Apache License 2.0

Python 100.00%
python python3 metadata metaprogramming syntax robustness development-tools powerful linq csharp

linqit's Introduction

Linqit!

Extends python's list builtin with fun, robust functionality - .NET's Language Integrated Queries (Linq) and more.
Write clean code with powerful syntax.

pip install linqit


Stop using loops, complex conditions, list comprehension and filters.
Doesn't it looks better?

from linqit import List

# Go ahead and fill the list with whatever you want... like a list of <Programmer> objects.
programmers = List()
Avi = type("Avi", (), {})
Entrepreneur = type("Entrepreneur", ('talented'), {})
elon_musk = Entrepreneur(talented=True)

# Then play:
last_hot_pizza_slice = (
    programmers.where(lambda e: e.experience > 15)
    .except_for(elon_musk)
    .of_type(Avi)
    .take(3)  # [<Avi>, <Avi>, <Avi>]
    .select(lambda avi: avi.lunch)  # [<Pizza>, <Pizza>, <Pizza>]
    .where(lambda p: p.is_hot() and p.origin != "Pizza Hut")
    .last()  # <Pizza>
    .slices.last()  # <PizzaSlice>
)

# What do you think?

We all use multiple aggregations in our code, while multiple filters/comprehensions are not pythonic at all.
The whole idea is is to use it for nested, multiple filters/modifications :).
Some of the methods might look ridiculous for a single calls, comparing to the regular python syntax.
Here are some use cases:

Methods:

all
any
concat
contains
distinct
except_for
first
get_by_attr
intersect
last
select
skip
take
where
of_type

Properties:

sum
min
max
avg
sorted

Deeper - Let's play with a list of people, a custom type.

import List

class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f'Person(name="{self.name}", age={self.age})')


# Creating a list of people
avi, bill, bob, harry = Person('Avi', 23), Person('Bill', 41), Person('Bob', 77), Person('Harry', 55)

people = List(avi, bill, bob, harry)

Use LINQ selections, write cleaner code

people = people.where(lambda p: p.age > 23) # [<Person name="Bill" age="41">, <Person name="Bob" age="77">, <Person name="Harry" age="55">]
people.first()                                              # <Person name="Bill" age="41">
people.last()                                               # <Person name="Harry" age="55">
people.any(lambda p: p.name.lower().startswith('b'))        # True
people.where(age=55)                         # [<Person name="Harry" age="55">]
people.skip(3).any()                                        # False
people.skip(2).first()                                      # <Person name="Harry" age="55">

# Isn't it better than "for", "if", "else", "filter", "map" and list comprehensions in the middle of your code?

More selections

new_kids_in_town = [Person('Chris', 18), Person('Danny', 16), Person('John', 17)]
people += new_kids_in_town # Also works: people = people.concat(new_kids_in_town)

teenagers = people.where(lambda p: 20 >= p.age >= 13)
danny = teenagers.first(lambda t: t.name == 'Danny')            # <Person name="Danny" age="16">
oldest_teen = teenagers.order_by(lambda t: t.age).last()                                  # <Person name="John" age="17">

Let's make python more dynamic

names = people.name                                             # ['Avi', 'Bill', 'Bob', 'Harry', 'Chris', 'John']
ages = people.age                                               # [23, 41, 77, 55, 18, 17]
teenagers_names = teenagers.name                                # ['Chris', 'Danny', 'John']
teenagers_names.take(2).except_for(lambda n: n == 'Danny')      # ['Chris']
teenagers.age.min                                               # 16
teenagers.age.avg                                               # 17
teenagers.age.max                                               # 18

Test Coverage

linqit git:(master) ✗ coverage report                    
Name                  Stmts   Miss  Cover
-----------------------------------------
linqit/__init__.py        2      0   100%
linqit/linq_list.py     101     11    89%
tests/__init__.py         0      0   100%
tests/test_list.py      203      0   100%
-----------------------------------------
TOTAL                   306     11    96%

linqit's People

Contributors

alexandre avatar avilum avatar fiendish avatar hucker avatar mikeckennedy avatar vpoulailleau avatar wadevries avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

linqit's Issues

A bug at the project description page

new_kids_in_town = [Person('Chris', 18), Person('Danny', 16), Person('John', 17)]
people += new_kids_in_town # Also works: people = people.concat(new_kids_in_town)

teenagers = people.where(lambda p: 20 >= p.age >= 13)
danny = teenagers.first(lambda t: t.name == 'Danny')            # <Person name="Danny" age="16">
oldest_teen = teenagers.last()                                  # <Person name="Chris" age="18">

.last() method doesn't return max age but the last in the list, right? Should return "John,17 yo" then.

Add support for short circuit all/any

In looking at the code I can see that the all/any methods traverse the whole list. I have a tested fix with short circuiting for these methods...but have never done pull requests...

Wrong example in README

The README says:

from linqit import List


programmers = List()
Avi = type('Avi', (), {})

# Go ahead and fill the list with whatever you want... like a list of <Programmer> objects.

# Then play:
last_hot_pizza_slice = programmers.where(lambda e:e.experience > 15)
                      .except_for(elon_musk)
                      .of_type(Avi)
                      .take(3) # [<Avi>, <Avi>, <Avi>]
                      .select(lambda avi:avi.lunch) # [<Pizza>, <Pizza>, <Pizza>]
                      .where(lambda p:p.is_hot() and p.origin != 'Pizza Hut').
                      .last() # <Pizza>
                      .slices.last() # <PizzaSlice>
                      
# What do you think?

I think there's a syntax error… .except_for(elon_musk) is not part of the last_hot_pizza_slice = … statement. You may add parenthesis around the whole statement.

I also think that there is an extra dot after p.origin != 'Pizza Hut')

You may also use black to format the code. This would finally give:

from seven_dwwarfs import Grumpy, Happy, Sleepy, Bashful, Sneezy, Dopey, Doc
from linqit import List


programmers = List()
Avi = type("Avi", (), {})

# Go ahead and fill the list with whatever you want... like a list of <Programmer> objects.

# Then play:
last_hot_pizza_slice = (
    programmers.where(lambda e: e.experience > 15)
    .except_for(elon_musk)
    .of_type(Avi)
    .take(3)  # [<Avi>, <Avi>, <Avi>]
    .select(lambda avi: avi.lunch)  # [<Pizza>, <Pizza>, <Pizza>]
    .where(lambda p: p.is_hot() and p.origin != "Pizza Hut")
    .last()  # <Pizza>
    .slices.last()  # <PizzaSlice>
)

# What do you think?

BTW, your project seems fun to try, thanks for what you've done.

Add support for order_by?

Hey, great library. I would love to do something like this but seems to just use the substandard built-in list implementation which returns None:

people = List()
people.append(Person("Michael", 47))
people.append(Person("Sarah", 50))
people.append(Person("Jake", 42))

older = people.where(lambda p: p.age > 43).sort(lambda p: -p.age)

But sadly, sort returns None and I didn't see an order_by, what am I missing?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.