1

Consider the following simple example:

import pandas as pd
mytable = pd.read_csv('test.dat',sep='\t')
mytable["z"] = mytable.x + mytable.y
mytable["q"] = mytable.z**2
mytable

for example with cat test.dat:

x       y
1       5
2       6
3       7
4       8

If I use something like this for example from ipython3 I want to "factor out" the mytable keyword as in this pseudo code:

import pandas as pd
mytable = pd.read_csv('test.dat',sep='\t')
cd mytable
   z = x + y
   q = z**2
mytable

Are there any possibilities to simplify syntax like this. It is ok, if the solutions uses additional ipython features.

Remark: I used a "cd" keyword following pgf/tikz syntax where something like this is possible.

1
  • 1
    Sounds like the with keyword from Pascal. I think there is no such thing in Python possible without massive hacking. After all Python strives to keep each line expressive without too much context. Think of the explicitness of self in methods which is exactly the opposite of your approach. See also stackoverflow.com/questions/2279180/… for the same question in C/C++. Commented Mar 3, 2017 at 10:51

1 Answer 1

1

Python's design does not really allow for this as it would lead to ambiguities. See here for a detailed discussion on the topic.

Consider a code like this:

class X(object):
  def __init__(self, q):
    self.q = q

x = X(4)
q = 3

# del x.q

with x:
  print q

This should print 4, I assume.

Now, consider to enable the del statement. Should this then raise an error (because of the missing q in x?) or should it print 3 (because of the more global variable q)? Since this is hard to decide and different people could validly have different opinions, Python decided not to have this feature at all.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.