0

When defining a class in Python, why does the class usage need to be in a new line? This becomes a bit annoying when trying to run python programs from a string (python -c '....') because I can't define and use the class on the same line. Is there a way to achieve this?

For example, the following fails:

$ cat class_play.py
class ClassA(): pass; a = 3; print(a); print(ClassA)
$ class ClassA(): pass; a = 3; print(a); print(ClassA)
$ python class_play.py
3
Traceback (most recent call last):
  File "class_play.py", line 1, in <module>
    class ClassA(): pass; a = 3; print(a); print(ClassA)
  File "class_play.py", line 1, in ClassA
    class ClassA(): pass; a = 3; print(a); print(ClassA)
NameError: name 'ClassA' is not defined

but using the class in a new line works:

$ cat class_play.py
class ClassA(): pass; a = 3; print(a);
print(ClassA)
$ python class_play.py
3
<class '__main__.ClassA'>
fersarr
  • 3,399
  • 3
  • 28
  • 35

1 Answers1

7

Use newlines, the command line is not limited to a single line:

python -c "
class Foo:
    pass
print(Foo())
"

or just insert \n sequences in a $'...' string

python -c $'class Foo:\n    pass\nprint(Foo())'

Using semi-colons, you can only add more simple statements, and they all fall within the same compound statement if you started the line with one. You can't use these to define methods or expect a class statement to have completed, you are still in the class definition.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343