Semzem
Semzem

Reputation: 93

Unusable function arguments

Is there a syntax for user-inaccessible arguments in Python functions. Or is that even possible?

For example, I would like to define a function that takes only a single argument from the user but there is a need for another argument where the function needs to call itself in a different setting, such as:

def function(userEntry, key1 = 0):
    if key1 == 0: #setting 1 
        ##SOME INITIAL OPERATIONS ##
        key1 += 1
        function(userEntry, key1)
    if key1 == 1: #setting 2
        ##FINAL OPERATIONS##
        print('Some function of ' userEntry) 

If done as above, user can still access key1 and initialize the program as they wish, however, I do not want user to be able to do this. I want the user to enter userEntry only while the function requires to call itself depending on the conditions on user-input and key1, operations will change.

Upvotes: 3

Views: 247

Answers (3)

progmatico
progmatico

Reputation: 4964

By your latest comment it looks that perhaps you want something like this:

class OffsetedIncrementer:
    _offset = 100

    def __init__(self, offset=100):
        OffsetedIncrementer._offset = offset

    def inc(self, x):
        return x + 1 + OffsetedIncrementer._offset


oi = OffsetedIncrementer(200)
func = oi.inc

print(func(2))

Output:

203

Upvotes: 0

Jelly Joe
Jelly Joe

Reputation: 48

I agree that having a separate function that the user calls would be a good idea. I have made some code that works for that here:

key = 0

def userFunc(input):
    # Do stuff
    function(input, key)

def function(userEntry, key1 = 0):
    if key1 == 0: #setting 1 
        ##SOME INITIAL OPERATIONS ##
        print('initial operation')
        print key1
        key1 += 1
        return ##to make the function not instantly repeat itself
    if key1 == 1: #setting 2
        ##FINAL OPERATIONS##
        print('final operation')
        print key1

userFunc('inValue')

This would do the initial operations the first time userFunc() is called, then the final operations the next time it is called.

Upvotes: 2

Sayse
Sayse

Reputation: 43300

Have a function that the end user calls, that does what it needs to, before calling the actual function which you use everywhere else.

def userFunc(input):
    # Do stuff
    function(input, key)

def function
    # Does common functionality

Upvotes: 2

Related Questions