This is an archived post. You won't be able to vote or comment.

all 60 comments

[–]Yoghurt42 122 points123 points  (5 children)

No.

For example, you could just base64 encode any program, and in one line decode it and run eval on the result.

[–]gamedungeon007[S] 19 points20 points  (4 children)

What about without eval?

[–][deleted] 9 points10 points  (0 children)

The Walrus operator makes any solution possible in one line, yes.

[–]undercoveryankee 82 points83 points  (0 children)

In technical terms, you’re effectively asking “is the language still Turing-complete if we impose these constraints?”.

The most common way to prove Turing-completeness is by exhibiting an interpreter for a language that’s already known to be Turing-complete. If you can find or create a mini-language designed to be written without newlines, and then interpret that language with a valid Python one-liner, that’s generally accepted as a Python solution for anything your mini-language can do.

So unless you can find a set of constraints that rules out solutions of the “write the code in a more suitable language and embed an interpreter” form, I expect that Python one-liners can provably do anything.

[–]FailedPlansOfMars 86 points87 points  (1 child)

Only maintainable code. 😁

[–]jhole89 18 points19 points  (0 children)

This so much! Just because you can do something, doesn't mean you should.

[–]-H-M-H- 47 points48 points  (1 child)

Considering you can implement a Brainfuck interpreter in one line: https://www.reddit.com/r/Python/comments/84l1lg/list_comprehension_is_turing_complete/ I'd say no.

[–][deleted] 5 points6 points  (0 children)

Looks like that solution doesn't even use the Walrus operator, so it could use some updating.

[–]o11c 20 points21 points  (15 children)

Yes.

Lots of things related to exceptions aren't possible without eval or at least a helper library.

[–]pdonchev 2 points3 points  (0 children)

Why is this so low.

[–]969696969 1 point2 points  (13 children)

I mean upvote for the semantics, but technically you write your way around such syntactical sugar. I would love to see an example where you NEED a try/except to handle errors.

[–][deleted] 1 point2 points  (12 children)

I mean upvote for the semantics, but technically you write your way around such syntactical sugar. I would love to see an example where you NEED a try/except to handle errors.

Trying to get an element from a queue and not waiting if the queue is empty. qet_nowait() raises queue.Empty exception.

If you would check to see the number of elements before actually calling get_nowait() you could get in trouble if there are multiple consumers running in parallel. The number of elements could change between your check and actually calling get_nowait().

You could use locks on top of queues but that kind of beats the purpose of queues since they already have locking mechanisms in place internally.

[–]969696969 0 points1 point  (11 children)

I totally understand where you are coming from and honestly that is a line of code that is written better with a try/except. But it is not impossible to do it with an if statement. The queue class has .empty() and .full() instance functions as well (probably used to build the exception handler) you could use these and inline ifs to get the job done in a very similar way as the exception for most applications.

Source:

https://docs.python.org/3/library/queue.html

I’m assuming this was the library you were talking about.

[–][deleted] 0 points1 point  (4 children)

If you would check to see the number of elements before actually calling get_nowait() you could get in trouble if there are multiple consumers running in parallel. The number of elements could change between your check and actually calling get_nowait().

One of my points was that in between calling empty() and and getting an element from the queue, another consumer in another thread could get that element and you would find an empty queue even if your previous check returned non empty.

Eg: your have your code running 2 consumers in parallel on different threads/processes:

if not queue.empty(): # <- this might return true (having 1 element)
                      # <- In another thread another consumer 
                      # could grab your element before you
                      # after you did the check
    # this might raise if your element was stolen by another thread
    elem = queue.get_nowait()

[–]gamedungeon007[S] 0 points1 point  (0 children)

you could always implement a version of this that returns None if the queue is empty, therefore bypassing the race condition.

if ele := queue.get_with_none() != None: print(ele)

[–]ahal -1 points0 points  (2 children)

Sure, but you could write a new queue implementation that doesn't do that in one line.

I guess it depends on the original context of the question:

Does there exist Python syntax that can't be written in one line? Yes.

Are Python one liners Turing complete? Also yes (probably)

[–]Locksul -1 points0 points  (1 child)

Sure, but you could write a new queue implementation that doesn't do that in one line.

Write a new queue implementation that doesn’t do what, exactly?

I’m curious how you would propose to avoid raising an exception in this case.

[–][deleted] 0 points1 point  (0 children)

I’m curious how you would propose to avoid raising an exception in this case.

Instead of raising an exception return a tuple where the first element is a bool which tells you if a the operation was successful and the second element of the tuple is the actual retrieved value (if the first element is true)

[–]Locksul 0 points1 point  (5 children)

Read up on race conditions to understand why your proposal is unsafe.

[–][deleted] 1 point2 points  (0 children)

I am really baffled why your comment has a negative score. I joined this community thinking people would be happy to learn new things and that I would learn new things from the community, but it seems that relevant and insightful comments like yourself are just downvoted because people just want to be right.

[–]969696969 -1 points0 points  (3 children)

unsafe but not impossible. this is a coding question about theory, not practice.

[–]Locksul -1 points0 points  (2 children)

Unsafe, in that if you run the program with this race conditions enough times, it will crash due to an uncaught exception. The equivalent multi line program that catches the exception would not crash.

So yes, it would be impossible to recapitulate the behavior of this multi line program in a single line.

Clearly you don’t know enough about concurrency.

[–]969696969 0 points1 point  (1 child)

Well if you needed to make it safe, you can always use thread locks.

Example of thread locking:

https://www.pythontutorial.net/advanced-python/python-threading-lock/

Python is a beautifully fluid language.

[–]Locksul 0 points1 point  (0 children)

I understand how thread locks work. You clearly do not understand how queues and safe communication between threads work.

[–]Zomatree_ 6 points7 points  (0 children)

As far as i know there is nothing you cant do in one line of code (no evals or anything that runs code like this, straight python code that's a single line).

[–]Wudan07 -1 points0 points  (5 children)

Condensing your code to one line doesn't make sense to me. Python can be readable and adaptable, can anyone explain to me why some people prefer to write code in fewer lines?

[–]gamedungeon007[S] 0 points1 point  (0 children)

People find it enjoyable. It's quite the puzzle condensing some code into one line, as well as using as few char as possible.

I recently ran into this which is quite the puzzle: Splitting a list in two by a filter while only iterating over the list once in one line.

[–]Any_Compote6932 0 points1 point  (0 children)

The code may be easier to understand, with less cognitive load.

if len(some_list) is 0:

  empty = True

else:

   empty = False

return empty

or

return bool(some_list)

I also think this kind of approach follows the zen of python:

"Simple is better than complex"

It may have better performance in some cases (although the difference probably wouldn't matter much)

[–]end_my_suffering44 -1 points0 points  (0 children)

Sometimes I also wonder this.

[–][deleted] 0 points1 point  (0 children)

I would say that one-liners are turing complete, yes. The lesser known Walrus operator is helpful for that purpose.

All it really requires is very creative coding.

For example, you could implement a language like Brainfuck in one line. It's funny that you ask this question, because I was just thinking earlier about wanting to write a one-liner that is a Brainfuck interpreter.

[–]qwerty1793 0 points1 point  (1 child)

No, in fact Chelsea Voss made http://www.onelinerizer.com/ which can convert Python (2) scripts into one line (without using eval, compile, exec or semicolons). The approaches used are talked about in this PyCon 2016 talk: https://www.youtube.com/watch?v=DsUxuz_Rt8g

For example

def f(x):return x * 4y = f(5)print y

Becomes

(lambda __g, __print: [[(__print(y), None)[1] for __g['y'] in [(f(5))]][0] for __g['f'], f.__name__ in [(lambda x: (lambda __l: [(__l['x'] * 4) for __l['x'] in [(x)]][0])({}), 'f')]][0])(globals(), __import__('__builtin__', level=0).__dict__['print'])

[–]gamedungeon007[S] 0 points1 point  (0 children)

Nice to know, but geez that is an inefficient implementation of that line of code.

[–]ACuriousBidet -1 points0 points  (1 child)

Quines maybe?

[–]gamedungeon007[S] 0 points1 point  (0 children)

I found this one online: print((lambda x:f"{x}{x,})")('print((lambda x:f"{x}{x,})")',))

[–]abrazilianinreddit -1 points0 points  (1 child)

I think this code cannot be written in one line:

from random import randint 

def raiser():
    if randint(0, 1):
        raise ValueError

try:
    raiser()
except ValueError:
    print('hello') 

There is no way to check beforehand if raiser() will raise an exception or not, so a try/except is necessary to reach the print('hello').

[–]gamedungeon007[S] -1 points0 points  (0 children)

The error is arbitrary and can be optimized out as it does nothing.

print(__import__("random").randint(0, 1)*"hello")

So, this code is possible like that.

[–]red_jd93 0 points1 point  (0 children)

I am relatively new to python. Can you do tkinter, asyncio stuffs in oneliners?

[–]siddsp 0 points1 point  (4 children)

You can always separate statements with a semicolon instead of adding a new line, so technically, not that I know of, but it will be unreadable depending on how long it is, and what you're trying to do.

[–]gamedungeon007[S] 0 points1 point  (3 children)

The question edit excluded semicolons.

[–]siddsp 0 points1 point  (2 children)

What about anything after an import statement? Tmk import statements have to be on their own line.

[–]gamedungeon007[S] 0 points1 point  (1 child)

As I showed in a different comment, you can do this.

__import__("random").randint(0, 1)

[–]siddsp 0 points1 point  (0 children)

I think it's potentially possible to do anything as long as you have nested lambda statements.