Reputation: 23
I want to implement something similar to the return of os.get_terminal_size
print(myFunction())
myFunction(a=1, b=2)
print(myFunction().a) # 1
print(myFunction().b) # 2
example:
import os
os.get_terminal_size()
'os.terminal_size(columns=169, lines=40)'
os.get_terminal_size().columns
169
type(os.get_terminal_size)
'<class 'os.terminal_size'>'
How can I do that?
Upvotes: 1
Views: 362
Reputation: 8247
My interpretation of your question is that you want to implement get_terminal_size
yourself in a different way.
shutil.get_terminal_size
wraps os.get_terminal_size
and basically performs an optimization where it looks up your ${COLUMNS}
and ${LINES}
environment variables as a shortcut. Failing the lookup, it defers to os.get_terminal_size
. Its source code is here.
As for the implementation of os.get_terminal_size
, it is written in c
and under the hood leverages either ioctl or conio.h. The code lives here.
Upvotes: 1
Reputation: 142641
type(os.get_terminal_size)
shows that it is a class, not function.
First line also shows that it has method __str__
to display formatted text with values
class MyClass:
def __init__(self):
self.columns = 169
self.lines = 40
def __str__(self):
return 'MyClass(columns={}, lines={})'.format(self.columns, self.lines)
print(MyClass())
# MyClass(columns=169, lines=40)
print(MyClass().columns)
# 169
EDIT:
It also doesn't get arguments but if you want to arguments then you would need
class MyClass:
def __init__(self, columns=169, lines=40):
self.columns = columns
self.lines = lines
def __str__(self):
return 'MyClass(columns={}, lines={})'.format(self.columns, self.lines)
print(MyClass())
# MyClass(columns=169, lines=40)
print(MyClass(columns=1, lines=2))
# MyClass(columns=1, lines=2)
But it can't keep values - it would need instance of class to keep them.
print(MyClass(columns=1, lines=2).columns)
# 1
print(MyClass().columns)
# 169
my_instance = MyClass(columns=1, lines=2)
print(my_instance.columns)
# 1
Upvotes: 2