0

I want to create a function that would behave differently depending on how the input is passed to it.

For example:

def my_func(a):
   if is_constant_input(a): # Does something like this conditional exist?
      print(f"A constant input {a} was passed")
   else:
      print(f"A variable input {a} was passed")

then I call the function in two ways.

First way:

val = [1, 2, 3]
my_func(val) # A variable input [1, 2, 3] was passed.

Second way:

my_func([1, 2, 3]) # A constant input [1, 2, 3] was passed.

I want to know if there's a way to implement that is_constant_input() conditional?

EDIT: fixed the example by using an mutable argument (e.g., a list)

Rehan Rajput
  • 112
  • 8
  • 4
    What's the usecase of this requirement? – matszwecja May 09 '22 at 11:50
  • 1
    sounds like a XY problem – Julien May 09 '22 at 11:50
  • Nope, not possible. (In any feasible/sane way). – timgeb May 09 '22 at 11:54
  • The same object (`42` in this case) is passed in both cases, the fact that in one case a reference points to it is not visible by the function. – Julien May 09 '22 at 11:56
  • Are you perhaps thinking that 'constant' is equivalent to immutable? – DarkKnight May 09 '22 at 11:56
  • @Julien the same object is passed only because small integers are cached, that's a special case. – timgeb May 09 '22 at 11:56
  • @timgeb wouldn't it be the case with any object? – Julien May 09 '22 at 11:57
  • 1
    This isn't something that gets represented in Python's data model: variables are just names associated with values, and `a` just gets bound to a value, with no indication of whether the *source* used a literal or another variable (or more complicated expression) to provide that value. If you really need this for some reason, you would have to use something like the `inspect` module to examine the actual source code. – chepner May 09 '22 at 11:57
  • @Julien no, consider `def my_func(a): a.append(1)` and call it with `my_func(val)`, where `val` is a list `[1, 2, 3]`. Then call it with `my_func([1, 2, 3])` directly to see the difference. (In the first case, `val` is mutated.) – timgeb May 09 '22 at 11:58
  • 1
    @timgeb not the point I was making, but yeah my wording is ambiguous. I mean same object value, not same object id. – Julien May 09 '22 at 12:01
  • I have a bad example. My specific use-case is more related to mutable arguments (e..g, a `list`). I'll update the example. – Rehan Rajput May 09 '22 at 12:01
  • @Julien yes that's correct. – timgeb May 09 '22 at 12:01
  • 3
    @RehanRajput lists are not an example of immutable objects – DarkKnight May 09 '22 at 12:02
  • and the answer is still no :) – timgeb May 09 '22 at 12:03
  • but I'm curious why do you want to do this? – timgeb May 09 '22 at 12:03
  • 1
    Very good discussion from 10+ years ago but still valid:- https://stackoverflow.com/questions/4374006/check-for-mutability-in-python – DarkKnight May 09 '22 at 12:06

0 Answers0